I have a list, whose indices are mostly integer numbers, but occasionally, there are some 'X' entries. I need all of the entries to perform list operations with this list and another list. How can I replace the 'X' entries which are strings with integers zeroes, while keeping the lists the same length.
I've tried using if statements to replace the entry if it is an 'X', but that just gave me a type error.
Example: changing
['X', 'X', 52, 39, 81, 12, 'X', 62, 94]
to
[0, 0, 52, 39, 81, 12, 0, 62, 94]
in which all entries in the second list are int.
Try to use map to do this:
>>> l= ['X','X',52,39,81,12,'X',62,94]
>>>
>>> map(lambda x:0 if x=="X" else x,l)
[0, 0, 52, 39, 81, 12, 0, 62, 94]
If you're using Python3.x , map() returns iterator, so you need to use list(map()) to convert it to list.
Or use list comprehension:
>>> [i if i!='X' else 0 for i in l]
[0, 0, 52, 39, 81, 12, 0, 62, 94]
First of all, you need to improve your use of terminologies. The indices are all integers, it is the elements that are a mix of strings and integers.
Solution
l = ['X', 'X', 52, 39, 81, 12, 'X', 62, 94]
l = [0 if element == 'X' else element for element in l]
print(l)
Better Performance Solution, with in-place replace
l = ['X', 'X', 52, 39, 81, 12, 'X', 62, 94]
for i in range(len(l)):
l[i] = 0 if l[i] == 'X' else l[i]
print(l)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With