gpt4 book ai didi

python - 在 python 中遍历文本文件中的列

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:57 26 4
gpt4 key购买 nike

我有一个以下格式的文本文件:

1,"20130219111529","90UP:34","0000","9999","356708","2"
"-2","20130219105824","0001:11","0000","","162_005",""

出于某种目的,我想比较第 1 行和第 2 行(在本例中为 1 和 -2)。要删除所有引号并解析此文件,我有以下代码:

if os.path.exists(FileName):
with open(FileName) as File:
for row in csv.reader(File, delimiter= ',', skipinitialspace= True):
print(row)

输出如下:

['1', '20130219111529', '90UP:34', '0000', '9999', '356708', '2']
['-2', '20130219105824', '0001:11', '0000', '', '162_005', '']

我想遍历列。例如,遍历“1”然后“-2”等等。

我该怎么做?

最佳答案

使用zip()。它将两个可迭代对象变成一个可迭代的元组,元素来自两个列表。

l1 = ['1', '20130219111529', '90UP:34', '0000', '9999', '356708', '2']
l2 = ['-2', '20130219105824', '0001:11', '0000', '', '162_005', '']

for elem1, elem2 in zip(l1, l2):
print("elem1 is {0} and elem2 is {1}.".format(elem1, elem2)

关于python - 在 python 中遍历文本文件中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597282/

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