Python:将正整数和负整数的列表元素字符串转换为int?

标签 python python-3.x list

我正在为此绞尽脑汁。我需要遍历嵌套列表(列表列表,因此只有一层子列表)来检查条目是正整数还是负整数。如果是,我需要将其转换为 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/

相关文章:

python - 为 Anaconda 创建离线包文件夹

Python 打包 : Generate a python file at installation time, 与 tox 一起工作

javascript - 从 jquery 到 Django 进行 ajax 调用时未设置 CSRF

类属性中的Python循环导入

python-3.x - python脚本无法显示 “missing parenthesis in call to ' print'”

python - 如何随机替换嵌套列表中的特定元素?

CSS - li 元素在 IE 中无法正确显示

Java - 创建一个包含固定 40 个元素的数组的列表

python - 直方图中绘图的百分比变化

python - tkinter - wm 协议(protocol)不处理 WM_HELP 消息