【问题标题】:Python double loop for dictdict的Python双循环
【发布时间】:2014-11-27 20:00:13
【问题描述】:

我有这样的 csv 文件:

fio,username,otdel
Andrey,a.andrey,it
Vlad,v.vlad,support
Love,l.love,bill
Vasy,v.pupkin,main

我需要像这样混合它

User,fio2,username2,otdel2
a.andrey,Vlad,v.vlad,support
a.andrey,Love,l.love,bill
a.andrey,Vasy,v.pupkin,main
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main
.....

我做了这个代码:

import csv
def mixusr(filecsv):
    csvfile = csv.DictReader(open(filecsv), delimiter=",")
    outfile = csv.writer(open('pile.csv', 'w'), delimiter=',')
    outfile.writerow(['User', 'fio2', 'username2', 'otdel2'])
    for key in csvfile:
        outfile.writerow([key['username'], key['fio'], key['username'], key['otdel']])
        for xkey in csvfile:
            outfile.writerow([key['username'], xkey['fio'], xkey['username'], xkey['otdel']])


mixusr('list.csv')

但它会停止迭代,输出是

User,fio2,username2,otdel2
v.vlad,Vlad,v.vlad,support
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main

我做错了什么。 当我这样做时

def mixusr(filecsv):
    csvfile = csv.DictReader(open(filecsv), delimiter=",")
    **csvfile2 = csv.DictReader(open(filecsv), delimiter=",")**
    outfile = csv.writer(open('pile.csv', 'w'), delimiter=',')
    outfile.writerow(['User', 'fio2', 'username2', 'otdel2'])
    for key in csvfile:
        outfile.writerow([key['username'], key['fio'], key['username'], key['otdel']])
        for xkey in **csvfile2**:
            outfile.writerow([key['username'], xkey['fio'], xkey['username'], xkey['otdel']])

我明白了:第二次迭代不起作用,我不知道有什么问题!!帮助

User,fio2,username2,otdel2
v.vlad,Vlad,v.vlad,support
v.vlad,Vlad,v.vlad,support
v.vlad,Andrey,a.andrey,it
v.vlad,Love,l.love,bill
v.vlad,Vasy,v.pupkin,main
a.andrey,Andrey,a.andrey,it
l.love,Love,l.love,bill
v.pupkin,Vasy,v.pupkin,main

【问题讨论】:

  • 我不经常使用csv模块,但我有一种感觉,你只能遍历一个csv文件一次。尝试第二次迭代它会给你零行。
  • 同意,问题是在两个循环中使用相同的读取器迭代器。内循环第一次迭代后,迭代器耗尽,外循环结束。参见例如here 类似问题。

标签: python csv dictionary iteration


【解决方案1】:

正如 cmets 中已经解释的那样,问题在于 csv reader 是一个迭代器,因此一旦你迭代它一次,它将是 exhausted,即外循环将在 first 之后结束 em> 内部循环的通过。

要解决此问题,您可以在内循环的每次迭代中创建一个新的阅读器,但我建议使用 itertools.product 来获取每个用户组合。

import csv
import itertools
def mixusr(filecsv):
    csvfile = csv.DictReader(open(filecsv), delimiter=",")
    outfile = csv.writer(open('pile.csv', 'w'), delimiter=',')
    outfile.writerow(['User', 'fio2', 'username2', 'otdel2'])
    for key, xkey in itertools.product(csvfile, repeat=2):
        if key != xkey:
            outfile.writerow([key['username'], xkey['fio'], xkey['username'], xkey['otdel']])

请注意,您只需调用一次outfile.writerow;代码中的第二次调用是必要的,因为第一项已被外部循环消耗。此外,虽然我的版本与您的“外观”示例相符,但您可能希望使用 itertools.combinations

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 2013-05-28
    • 2018-02-28
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多