我有三本不同的字典
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的实现有困难
不是100%确定你在问什么。我理解这个问题,您想知道如何最好地将
else
子句添加到这个复杂的三重if
语句中。你知道吗最好的方法不是有三个
if
语句,而是只有一个,并使用and
组合这些条件。你知道吗你也可以稍微改变一下条件,以防你觉得这更直观:
您还可以通过交换
if
和else
大小写来摆脱not
。你知道吗相关问题 更多 >
编程相关推荐