gpt4 book ai didi

python - 在 python 2.6 中逐行迭代两个文件的首选方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:09 25 4
gpt4 key购买 nike

Python 2.7之后,可以使用类似 this 的解决方案逐行迭代两个文件。但是,在早期版本的 Python 中,这不起作用并会给出无效语法错误。

我想知道使用 Python 2.6 执行此操作的最佳方法?

最佳答案

首选方式仍然相同,但 with 语句不支持单个语句中的多个对象。所以,你可能想像这样分割它

from itertools import izip

with open("Input1.txt") as textfile1:
with open("Input2.txt") as textfile2:
for x, y in izip(textfile1, textfile2):

根据PEP-0343 ,“规范:‘with’语句”部分,

A new statement is proposed with the syntax:

   with EXPR as VAR:
BLOCK

Here, with and as are new keywords; EXPR is an arbitrary expression (but not an expression-list) and VAR is a single assignment target. It can not be a comma-separated sequence of variables, but it can be a parenthesized comma-separated sequence of variables. (This restriction makes a future extension possible of the syntax to have multiple comma-separated resources, each with its own optional as-clause.)

关于python - 在 python 2.6 中逐行迭代两个文件的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com