从Python中的文件中读取包含整数的行? [英] Read lines containing integers from a file in Python?
问题描述
我有这样的文件格式:
9 8 1
3 4 1
。 ..
...
现在我想把每一行看作三个整数。
当我在f.readlines()中使用
:
print line.split()
脚本输出:
['9','8','1 \r\\\
']
['3',' 4','1 \r\\\
']
...
...
如何将每一行作为三个整数?
如何将列表转换为整数:你可以遍历每一行并将字符串转换为 int
以下示例使用列表理解:
Gi ven:
line = ['3','4','1 \r\\\
']
然后:
int_list = [int(i)for i in line]
将产生一个整数列表
[3,4,1]
,然后您可以通过下标(0到2)进行访问。例如
$ b
int_list [0]
包含 3
, p>
int_list [1]
包含 4
,
etc。
一个更简化的版本供您考虑:
with open('data.txt')as f:
for line in f:
int_list = [int (i)for line in line.split()]
print int_list
使用和
是因为它会在你完成后自动关闭你的文件,或者遇到异常。
<根据你的意见,如果你想在3个不同的变量,例如
一个数字 , b
和 c
,您可以执行以下操作: for line in f:
a,b,c = [int(i)for line in line.split()]
打印'a =%d,b =%d,c =%d\\\
'%(a,b,c)
得到这个:
$ $ $ $ $ $ c $ a = 9,b = 8,c = 1
这个数字在每行有3个数字。
注意,代替list comprehension(LC),您也可以使用生成器表达式 (GE):
a,b,c =(int(i)for i in line.split() )
对于3个整数的特定问题,这并没有太大的区别,但是我展示了它完整性。对于较大的问题,LC需要更多的内存,因为它一次生成一个完整的内存列表,而GE根据需要逐个生成一个值。这个问题生成器表达式与列表理解将给你更多的信息,如果你很好奇。
I have a file format like this:
9 8 1
3 4 1
...
...
Now, I want to get each line as three integers.
When I used
for line in f.readlines():
print line.split(" ")
The script printed this:
['9', '8', '1\r\n']
['3', '4', '1\r\n']
...
...
How can I get each line as three integers?
Using the code you have and addressing your specific question of how to convert your list to integers:
You can iterate through each line and convert the strings to int
with the following example using list comprehension:
Given:
line =['3', '4', '1\r\n']
then:
int_list = [int(i) for i in line]
will yield a list of integers
[3, 4, 1]
that you can then access via subscripts (0 to 2). e.g.
int_list[0]
contains 3
,
int_list[1]
contains 4
,
etc.
A more streamlined version for your consideration:
with open('data.txt') as f:
for line in f:
int_list = [int(i) for i in line.split()]
print int_list
The advantage of using with
is that it will automatically close your file for you when you are done, or if you encounter an exception.
UPDATE:
Based on your comments below, if you want the numbers in 3 different variables, say a
, b
and c
, you can do the following:
for line in f:
a, b, c = [int(i) for i in line.split()]
print 'a = %d, b = %d, c = %d\n' %(a, b, c)
and get this:
a = 9, b = 8, c = 1
This counts on there being 3 numbers on each line.
Aside:
Note that in place of "list comprehension" (LC) you can also use a "generator expression" (GE) of this form:
a, b, c = (int(i) for i in line.split())
for your particular problem with 3 integers this doesn't make much difference, but I show it for completeness. For larger problems, LC requires more memory as it generates a complete list in memory at once, while GE generate a value one by one as needed. This SO question Generator Expressions vs. List Comprehension will give you more information if you are curious.
这篇关于从Python中的文件中读取包含整数的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!