Python 将字符串子集转换为列表中的整数
我经常发现自己的清单如下所示:Python 将字符串子集转换为列表中的整数,python,Python,我经常发现自己的清单如下所示: lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D'] lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...] >>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D'] >>> indices
lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> indices = [1,2]
>>> [int(lst[x]) if x in indices else lst[x] for x in xrange(len(lst))]
['A', 1, 2, 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
将此列表中的特定字符串转换为int的最具python风格的方法是什么
我通常会这样做:
lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> indices = [1,2]
>>> [int(lst[x]) if x in indices else lst[x] for x in xrange(len(lst))]
['A', 1, 2, 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
上述方法似乎是错误的。是否有更好的方法将列表中的某些项转换为整数?我想说:
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> lst = [int(s) if s.isdigit() else s for s in lst]
>>> lst
['A', 1, 2, 'B', 1, 'C', 'D', 4, 1, 4, 5, 'Z', 'D']
int
和.isdigit
在Unicode情况下可能不一致,即int
可能无法解析字符串,即使.isdigit
为字符串返回True
def maybe_int(s):
try:
return int(s)
except ValueError:
return s
lst = [maybe_int(s) for s in lst]
@FatalError答案可能就是您要寻找的,但如果您只想将某些项目(不是所有数字)转换为整数,您可以执行以下操作:
lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> indices = [1,2]
>>> [int(lst[x]) if x in indices else lst[x] for x in xrange(len(lst))]
['A', 1, 2, 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
这也适用于浮动吗?我找不到相应的
isfloat()
方法。出于更一般的目的,您可以编写一个正则表达式来匹配,或者像@JFSebastian那样编写,并将转换包装在实用函数中的try/except块中。