简体   繁体   English

如何在python中逐行读取文件并逐元素读取列表元素

[英]How do I read a file line by line and read a list element by element simultaneous in python

I have a text file and a list of integers in python. 我有一个文本文件和python中的整数列表。 I want to read the contents of the file line by line whereas parse the elements of the list simultaneous. 我想逐行读取文件的内容,同时解析列表中的元素。

Here is an example of contents of the text file (myfile.txt): 这是文本文件(myfile.txt)内容的示例:

line1
line2
line3

and the list is: 列表是:

mylist = (1, 2, 3)

for example, I want to have a loop like below: 例如,我想要一个如下循环:

for line, item in open(myfile.txt), mylist:
  print line
  print item

and I expect to see this output: 我希望看到以下输出:

line1
1
line2
2
line3
3

Use zip : 使用zip

for line, item in zip (open ('myfile.txt'), mylist):
  print (line)
  print (item)

the loop will stop when the shortest of the iterables is exhausted. 当最短的可迭代对象耗尽时,循环将停止。

If you don't want to read the whole file in one go you could use itertools.izip if you using python2: 如果您不想一次读取整个文件,可以使用itertools.izip如果您使用的是python2):

for line, item in itertools.izip(open("myfile.txt", mylist)):
    print(line)
    print(item)

If you're using python3 you should use zip instead: 如果您使用的是python3,则应改用zip

for line, item in zip(open("myfile.txt", mylist)):
    print(line)
    print(item)

If you don't mind reading the file in one go you could use zip anyway (both for python2 and 3). 如果您不介意一次性阅读文件,则可以使用zip (适用于python2和3)。

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

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