简体   繁体   中英

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.

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 performance is a concern, you can use numpy :

>>> import numpy as np
>>> a=np.array(['X','X',52,39,81,12,'X',62,94])
>>> a[a=='X']=0
>>> a
array(['0', '0', '52', '39', '81', '12', '0', '62', '94'], 
      dtype='|S2')

Then if you want all ints:

>>> a.astype(int)
array([ 0,  0, 52, 39, 81, 12,  0, 62, 94])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM