简体   繁体   English

如何将文本文件中的数字作为数字读取到列表中?

[英]How to read numbers in text file as numbers in to list?

I have a text file in which there are numbers in each line(only numbers).我有一个文本文件,其中每行都有数字(只有数字)。 My color.txt looks like:我的color.txt看起来像:

3
3
5
1
5
1
5

When I read this to list using当我阅读本文以列出使用

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(line.strip('\n'))
    print g_colour_list

the output is like输出就像

['3', '3', '5', '1', '5', '1', '5']

But I want it as:但我希望它是:

[3,3,5,1,5,1,5]

How can I do that in the single line that is我怎么能在单行中做到这一点
g_colour_list.append(line.strip('\\n')) ? g_colour_list.append(line.strip('\\n')) ?

只需将您的字符串转换为整数:

g_colour_list.append(int(line.strip('\n')))

Wrap a call to python's int function which converts a digit string to a number around your line.strip() call:调用 python 的int函数,该函数将数字字符串转换为line.strip()调用周围的line.strip()

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(int(line.strip('\n')))
    print g_colour_list

One possible solution is to cast the string to integer on appending.一种可能的解决方案是在追加时将字符串转换为整数。 You can do it this way :你可以这样做:

g_colour_list.append(int(line.strip('\n')))

If you think you will get floats as well then you should use float() instead of int() .如果你认为你也会得到浮点数,那么你应该使用float()而不是int()

for line in f:
    g_colour_list.append(int(line.strip('\n')))

You can parse a string s to int with int(s)您可以使用 int(s) 将字符串 s 解析为 int

You can typecast it to int, doing:您可以将其类型转换为 int,执行以下操作:

f = open('color.txt',"r")
g_colour_list=[]

for line in f:
    g_colour_list.append(int(line.strip('\n')))

print (g_colour_list)

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

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