将类型'str'转换为分子/分母 [英] 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]
.
I'm having some trouble converting type 'str' to numbers. I use a separate text-file containing the following numbers 1, 2, 3, 4, 5, 6
and then I import these numbers into python and save them as a list. However, by doing this, I get a list of strings as follows: ['1', '2', '3', '4', '5', '6']
. I want to convert this list of strings so the list represents numbers, i.e. the output should be [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')
是否有执行此操作的特定命令?
Is there a specific command to do this?
推荐答案
You can use 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]
如果某些字符串虽然不能转换为数字,则可能会引发错误:
This can throw an error if there are strings that cannot be converted to numbers though:
l = ['1', '2', '3', '4', '5', 'lkj']
list(map(int, l))
ValueError:以10为底的int()无效文字:'lkj'
ValueError: invalid literal for int() with base 10: 'lkj'
因此请确保您输入的内容有效和/或将其包装为try/except
.
So make sure your input is valid and/or wrap it into a try/except
.
这篇关于将类型'str'转换为分子/分母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!