dict的Python双循环

时间:2014-10-02 18:45:04

标签: python csv dictionary iteration

我有这样的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

1 个答案:

答案 0 :(得分:0)

正如在评论中已经解释的那样,问题是csv reader是一个迭代器,因此一旦你迭代了它就会exhausted,即外部循环将在内循环的第一次传递。

要解决此问题,您可以在内循环的每次迭代中创建一个新的阅读器,但我建议使用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