Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace string in list with integer

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.

like image 924
Hidden Avatar asked Jan 22 '26 11:01

Hidden


2 Answers

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]
like image 103
McGrady Avatar answered Jan 23 '26 23:01

McGrady


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)
like image 28
EyuelDK Avatar answered Jan 24 '26 00:01

EyuelDK