我正在为此绞尽脑汁。我需要遍历嵌套列表(列表列表,因此只有一层子列表)来检查条目是正整数还是负整数。如果是,我需要将其转换为 int。问题是其他一些列表元素包含数字,因此我不能将包含数字的列表元素转换为 int,因为我收到错误。
我尝试过这个:
aList = ['a3','orange','-1','33']
for aLine in aList:
for token in aLine:
if token.isdecimal() == True:
map(int, aLine)
elif token in "0123456789" and token.isalpha() == False:
map(int, aLine)
...这对我的列表完全没有任何影响。
我希望得到这样的输出:
['a3', 'orange', -1, 33]
最佳答案
检查字符串 s
是否为整数的简单方法是执行 s.lstrip('+-').isdigit()
,它返回 对/错
。如果响应为 True
,您可以将其转换为 int(s)
,从而创建一个整数。
您可以根据响应创建新列表,或者如果您有索引值,则替换现有列表中的项目。这是一个简单的实现。
aList = ['a3','orange','-1','33']
bList = []
for s in aList:
if s.lstrip('+-').isdigit():
bList.append(int(s.lstrip('+-'))
else:
bList.append(s)
print bList
bList
结果如下
>>> bList
['a3', 'orange', -1, 33]
关于Python:将正整数和负整数的列表元素字符串转换为int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405179/