Reputation: 7
I have a tuple and list. I need to replace items in the list with values from tuple but on the way that I'm taking item from list comparing it with indexes in tuple and if there is some match I need to take value from tuple and to replace that item in list with that value.
If this is little bit confusing, here is a pseudeocode:
tuple = ('a','b','c','d','e','f','g','h','i')
list = ['1','4','8','3','b','g','x','4','z','r','0','0']
result = ['b','e','i','d','b','g','x','e','z','r','a','a']
I'm new in Python so I tried to implement some previous knowledge from C#, Java, JS, PHP etc but without success.
UPDATE: This is solution for my question, thank you people to you all!
input_tuple = ('a','b','c','d','e','f','g','h','i','j')
input_list = ['1','2','0','1','3','0','7','9','12','899']
lenght=len(input_tuple)-1 # find last index value in tuple
for i, v in enumerate(input_list):
#print (i, v)
result = [v if not v.isdigit() or int(v)>lenght else input_tuple[int(v)] for v in input_list] #slight modification "or int(v)>lenght" to avoid if number in list is bigger then index of tuple
print(result)
Upvotes: 0
Views: 198
Reputation: 17884
You can use the function map()
with some help function. For example:
t = ('a','b','c','d','e','f','g','h','i')
l = ['1','4','8','3','b','g','x','4','z','r','0','0']
def func(x):
if x.isdigit():
return t[int(x)]
else:
return x
r = list(map(func, l))
# ['b', 'e', 'i', 'd', 'b', 'g', 'x', 'e', 'z', 'r', 'a', 'a']
or listcomp:
r = [func(i) for i in l]
Upvotes: 0
Reputation: 104762
If I understand correctly, you want to replace numeric strings in your list with the corresponding string from the tuple, interpreting the numeric string as an index.
That's not too hard to do:
for i, v in enumerate(input_list):
if v.isdigit():
input_list[i] = input_tuple[int(v)]
Note that this modifies the input list in place. If you don't want to do that, you can instead create a new list with a list comprehension:
result = [v if not v.isdigit() else input_tuple[int(v)] for v in input_list]
Note that I'm not using your original names tuple
and list
because those are the names of the builtin types, and it's a bad idea to mask them (it can cause bugs if you want to call them in other code).
Upvotes: 2
Reputation: 430
Use '123'.isdigit()
to check whether values is digit or not.
t = ('a','b','c','d','e','f','g','h','i')
l = ['1','4','8','3','b','g','x','4','z','r','0','0']
[list(t)[int(el)] if el.isdigit() else el for el in l]
Output:
['b', 'e', 'i', 'd', 'b', 'g', 'x', 'e', 'z', 'r', 'a', 'a']
Upvotes: 0