[英]Converting a list of strings to a list of integers in Python
I have the following code which is used to extract a substring from each line of text on a file and put in a list of strings.我有以下代码,用于从文件的每一行文本中提取子字符串并放入字符串列表中。
distribution = []
with open("./Output_Files/datafile.txt", "r") as fileRead:
for line in fileRead:
distr_chop = line.split()[3:]
distribution.append(distr_chop)
Then I convert each string in the list to an integer:然后我将列表中的每个字符串转换为一个整数:
distribution = [int(i) for i in distribution]
However, I get an error when printing the list.但是,打印列表时出现错误。
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“列表”
distr_chop
is a list. distr_chop
是一个列表。
If it is a single element list, you can do如果是单元素列表,你可以这样做
...
distribution.append(distr_chop[0])
# then proceed to use the list comprehension to convert each element to an integer
dist_chop is in this case a list of 4th through nth "words" of the line thus distribution is an array of arrays which is not what I imagine you wanted.在这种情况下, dist_chop 是该行的第 4 到第 n 个“单词”的列表,因此分布是一个数组数组,这不是我想象的你想要的。
use distribution += distr_chop
if you actually wanted all the things after the 3rd or distribution.append(line.split())[3]
if you just wanted just one element from each line使用
distribution += distr_chop
如果你真的想要 3rd 之后的所有东西,或者distribution.append(line.split())[3]
如果你只想要每一行中的一个元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.