简体   繁体   English

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

[英]Python: Convert list element strings that are positive and negative integers to an int?

I'm wracking my brain with this. 我正在用这个来震撼我的大脑。 I need to iterate through a nested list (a list of lists, so only one level of sublist) to check if an entry is a positive or negative integer. 我需要遍历嵌套列表(列表列表,因此只有一个级别的子列表)来检查条目是正整数还是负整数。 If it is, I need to convert it to an int. 如果是,我需要将其转换为int。 The catch is that some other list elements contain numbers, so I can't just convert a list element containing numbers to an int because I get an error. 问题是其他一些列表元素包含数字,所以我不能只将包含数字的列表元素转换为int,因为我收到错误。

I tried this: 我试过这个:

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)

...Which did absolutely nothing to my list. ...这对我的名单绝对没有任何意义。

I'm hoping to get this kind of output: 我希望得到这种输出:

['a3', 'orange', -1, 33]

An easy way to check if a string s is an integer is by doing s.lstrip('+-').isdigit() which returns True/False . 检查字符串s是否为整数的简单方法是使用s.lstrip('+-').isdigit()返回True/False If the response is True you can cast it to int(s) which creates an integer. 如果响应为True ,则可以将其int(s)为创建整数的int(s)

You can create a new list from the responses or replace the item in the existing list if you have the index value. 如果您具有索引值,则可以从响应中创建新列表或替换现有列表中的项目。 Here's a simple implementation. 这是一个简单的实现。

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

The result of bList is as follows bList的结果如下

>>> bList
['a3', 'orange', -1, 33]

This probably is not the most pythonic answer but it works: 这可能不是最pythonic的答案,但它的工作原理:

assume 假设

x = [['2','-5'],['a23','321','x12']]

the code is: 代码是:

output = []
for row in x:
    temp = []
    for element in row:
        try:
            temp.append(int(element))
        except ValueError:
            temp.append(element)
    output.append(temp)

this gives you: 这给你:

[[2, -5], ['a23', 321, 'x12']]

Anothere solution using list comprehension : 使用列表理解的Anothere解决方案:

aList = ['a3', 'orange', '-1', '33']
results = [int(i) if i.lstrip('+-').isdigit() else i for i in aList]
print results

output: 输出:

['a3', 'orange', -1, 33]

Same can be achieved in one line using list comprehension. 使用列表推导可以在一行中实现相同。 ( Let me know if you need explanation) (如果您需要解释,请告诉我)

aList = ['a3', '14', 'orange', '-1', '33', '0'] aList = ['a3','14','orange',' - 1','33','0']

print([int(x) if x.lstrip('-').isnumeric() else x for x in aList ]) print([int(x)if x.lstrip(' - ')。isnumeric()else x for a in a]])

['a3', 14, 'orange', -1, 33, 0] ['a3',14,'orange',-1,33,0]

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

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