查找不在字典中的值

2024-09-23 22:21:39 发布

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

我有三本不同的字典

d1 = {'1': 1, '2': 2, '3': 3, '4' :4}
d2 = {'5': 5, '7': 7, '9': 9, '10' :10}
d3 = {'12': 12, '23': 23, '30': 30, '14' :14}

我想从一个文件中取一行,测试三列是否在那些字典中有值。如果三列中的值不在字典中,我想打印非匹配项对应的文件行。以下是我到目前为止写的:

OutputFileName = "results.txt"
OutputFile = open(OutputFileName, 'w')
import csv
with open('inputfile.txt') as f:
    reader = csv.DictReader(f,delimiter="\t")
    for row in reader:
        assign1 = row['assign1']
        assign2 = row['assign2']
        assign3 = row['assign3']
        if assign1 in d1: 

这就是我遇到困惑的地方。我只想要d1里没有的作业。这是我想做的一些伪类型代码:

if assign1 not in d1:
    if assign2 not in d2:
        if assign3 not in d3:
            OutputFile.write(''+assign1+'\t'+assign2+'\t'+assign3+'\n')

有没有一个简单的方法可以用字典做到这一点?我应该使用else语句吗?在这种情况下,我对else的实现有困难


Tags: 文件intxtif字典notrowd2
1条回答
网友
1楼 · 发布于 2024-09-23 22:21:39

不是100%确定你在问什么。我理解这个问题,您想知道如何最好地将else子句添加到这个复杂的三重if语句中。你知道吗

最好的方法不是有三个if语句,而是只有一个,并使用and组合这些条件。你知道吗

if assign1 not in d1 and assign2 not in d2 and assign3 not in d3:
    OutputFile.write(''+assign1+'\t'+assign2+'\t'+assign3+'\n')
else:
    # stuff to do when not in all three dicts

你也可以稍微改变一下条件,以防你觉得这更直观:

if not (assign1 in d1 or assign2 in d2 or assign3 in d3):

您还可以通过交换ifelse大小写来摆脱not。你知道吗

相关问题 更多 >