python - 用于if的嵌套循环

时间:2016-05-13 19:18:55

标签: python python-2.7 csv dictionary

我正在尝试解析字典中没有键的字符串。下面是代码。它与匹配的'完美匹配'但是当它写出字典中没有键的字符串时,它会写入重复。在确保字符串中没有键后,我只想写一次。

我无法弄清楚离开循环的方法。任何帮助将不胜感激。

    import csv
# Create Dictionary structure of csv file 2
with open("dict.csv", "rb") as fp:
    dic_file = csv.reader(fp,)
    dict1 = {}
    for d in dic_file:
        dict1[d[1]] = d[0]

print dict1

with open("match_out.csv", "wb") as fw1:
    with open("file.csv", "r") as fr1:
        with open("nomatch_out.csv", "wb") as fw2:
            output = csv.writer(fw1, delimiter=",")
            writer1 = csv.writer(fw2,delimiter=",")
            read = csv.reader(fr1,)     
            for row in read:
                for d in dict1:
                    if d == row[2]:
                        output.writerow(row) ## write only the matching ones

                    else:
                        writer1.writerow(row) ## if no key/match write to a separate file

1 个答案:

答案 0 :(得分:1)

一个简单的解决方法是测试临时布尔值(found_)如下:

import csv
# Create Dictionary structure of csv file 2
with open("dict.csv", "rb") as fp:
    dic_file = csv.reader(fp,)
    dict1 = {}
    for d in dic_file:
        dict1[d[1]] = d[0]

print dict1
found_ = None #not necessary

with open("match_out.csv", "wb") as fw1:
    with open("file.csv", "r") as fr1:
        with open("nomatch_out.csv", "wb") as fw2:
            output = csv.writer(fw1, delimiter=",")
            writer1 = csv.writer(fw2,delimiter=",")
            read = csv.reader(fr1,)     
            for row in read:
                found_ = False
                for d in dict1:
                    if d == row[2]:
                        found_ = True
                if found_:    
                    output.writerow(row) ## write only the matching ones
                else: 
                    writer1.writerow(row) ## if no key/match write to a separate file