用于di的Python双循环

2024-04-28 22:56:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的csv文件:

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

我需要这样混合

^{pr2}$

我做了这个代码:

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

Tags: csvcsvfilekeyusernameopenoutfilefioandrey
1条回答
网友
1楼 · 发布于 2024-04-28 22:56:38

正如在注释中已经解释的,问题是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。在

相关问题 更多 >