简体   繁体   English

将列表与字典值进行比较

[英]Comparing a list to dictionary values

I am supposed to be comparing a sentence to a set of keys:values and swapping certain words in the sentence with the corresponding values in the dictionary pairs.我应该将一个句子与一组键值进行比较,并将句子中的某些单词与字典对中的相应值进行交换。 Here is what I have so far:这是我到目前为止所拥有的:

keys = input().split(" ")
sentence = input().split(" ")
parent = {}
g = 0
for x in range(len(keys)):
    if x % 2:
        parent[first] = keys[x]
    else:
        first = keys[x]

for k,f in enumerate(sentence):
    if f is parent.keys():
        sentence[k] = parent.get(f,na)
    else:
        g+=1
print(sentence)
print(g)

The print statements in the bottom are just confirming the second loop is running.底部的打印语句只是确认第二个循环正在运行。 There are few other things I need to tidy up, but my main problem now is我需要整理的其他东西很少,但我现在的主要问题是

for k,f in enumerate(sentence):
    if f is parent.keys():
        sentence[k] = parent.get(f,na)

The first if keeps getting skipped over and I get my print(g) to output the number of loops it did;第一个 if 一直被跳过,我让我的 print(g) 输出它所做的循环数; which is all of them.这是全部。

Thanks!!谢谢!!

As others have said in comments you have a typo.正如其他人在评论中所说,你有一个错字。 if f is parent.keys(): should be if f in parent.keys(): or more succinctly if f in parent: if f is parent.keys():应该是if f in parent.keys():或者更简洁的if f in parent:

The reason for this error is that parent.keys() produces a list of keys, and you're attempting to check whether f is the same object as the keys of the dictionary.此错误的原因是parent.keys()生成一个键列表,并且您正在尝试检查 f 是否与字典的键是同一个对象。 What you were probably trying to do was check whether the string f existed within the list of keys.您可能试图做的是检查字符串 f 是否存在于键列表中。

For future reference x is y checks whether x and y refer to the same object.为了将来引用x is y检查 x 和 y 是否引用同一个对象。 x in y checks whether the value of x is present in the sequence y. x in y检查x in y的值是否存在于序列 y 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM