简体   繁体   English

python用整数替换列表中的字符串

[英]python replace string in list with integer

I have a list, whose indices are mostly integer numbers, but occasionally, there are some 'X' entries. 我有一个列表,其索引大多是整数,但偶尔会有一些'X'条目。 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. 如何用整数零替换字符串的'X'条目,同时保持列表长度相同。

I've tried using if statements to replace the entry if it is an 'X', but that just gave me a type error. 我尝试使用if语句替换条目,如果它是'X',但这只是给了我一个类型错误。

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. 示例:将[X,X,52,39,81,12,X,62,94]更改为[0,0,52,39,81,12,0,62,94] ,其中第二个列表中的所有条目是int。

Try to use map to do this: 尝试使用map来执行此操作:

>>> 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. 如果你使用的是Python3.x, map()返回迭代器,所以你需要使用list(map())将它转换为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 : 如果性能是一个问题,你可以使用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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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