繁体   English   中英

在python中将列表的特定元素从字符串更改为整数

[英]Change specific elements of a list from string to integers in python

如果我有一个列表如

c=['my', 'age', 'is', '5\\n','The', 'temperature', 'today' 'is' ,'87\\n']

我如何专门将列表的数字转换为整数,留下其余的字符串,并摆脱\\ n?

预期产量:

`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]`

我尝试使用'map()'和'isdigit()'函数,但它没有用。

谢谢。

您可以编写一个尝试转换为int的函数,如果失败则返回原始函数,例如:

def conv(x):
    try:
        x = int(x)
    except ValueError:
        pass
    return x

>>> c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']
>>> list(map(conv, c))
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
>>> [conv(x) for x in c]
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]

注意:由空格分隔的2个字符串由python自动连接,例如'today' 'is'相当于'todayis'

如果您不知道文本中整数的格式,或者只有太多的变体,那么一种方法就是在所有内容上尝试int()并查看成功或失败的内容:

original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n']
revised = []

for token in original:
    try:
        revised.append(int(token))
    except ValueError:
        revised.append(token)

print(revised)

通常使用tryexcept作为算法的一部分,不仅仅是你的错误处理,这是一种不好的做法,因为它们效率不高。 但是,在这种情况下,很难预测int()float()可以成功处理的所有可能输入,因此try方法是合理的。

暂无
暂无

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

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