[英]Convert type 'str' to numerator/ denominator
我在将类型“str”转换为数字时遇到了一些麻烦。 我使用一个单独的文本文件,其中包含以下数字1, 2, 3, 4, 5, 6
然后将这些数字导入 python 并将它们保存为列表。 但是,通过这样做,我得到了一个字符串列表,如下所示: ['1', '2', '3', '4', '5', '6']
。 我想转换这个字符串列表,以便该列表代表数字,即输出应该是[1, 2, 3, 4, 5, 6]
。
我的代码是:
def imported_numbers(filename):
with open(filename, 'r') as f:
contents = f.read().splitlines()
print(contents)
imported_numbers('sample.txt')
是否有特定的命令来执行此操作?
IMO 说起来更像是 Pythonic
str_list = ['1', '2', '3']
new_list = [int(n) for n in str_list]
如果您不确定所有字符串都是有效数字,则需要添加适当的错误处理。
您可以使用map
:
l = ['1', '2', '3', '4', '5', '6']
new_l = list(map(int, l)) # or just map(int, l) in Python 2
将返回
[1, 2, 3, 4, 5, 6]
如果存在无法转换为数字的字符串,这可能会引发错误:
l = ['1', '2', '3', '4', '5', 'lkj']
list(map(int, l))
ValueError:int() 的无效文字,基数为 10:'lkj'
因此,请确保您的输入有效和/或将其包装到try/except
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.