简体   繁体   English

TypeError:不可散列的类型:'set'/'list'

[英]TypeError: Unhashable type: 'set'/'list'

I am fairly new to programming and recently started working with dictionaries and a problem I am trying asks for me to create a list of names to take a poll.我对编程相当陌生,最近开始使用字典,我正在尝试的一个问题要求我创建一个姓名列表以进行投票。 2 names must not be in the dictionary while 2 more are in it. 2 个名字不能在字典中,而另外 2 个名字在字典中。 The code:编码:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil':  'python'
}
people = {'ryker', 'trey', 'jen', 'edward'}
for keys in favorite_languages:
    if people in favorite_languages:
        print(f"Thanks for taking our poll {people}")

To check if element exists in some List you use in operator, elem in list要检查您in运算符中使用的某些列表中是否存在元素,列表中的elem in list

print("1" in ["1", "2"]) # prints True

However elem need to be something [hashable][1].然而,elem 需要是 [hashable][1] 的东西。 For sure it cannot be set, but look here:肯定不能设置,但是看这里:

for keys in favorite_languages:
    if people in favorite_languages: # your elem = poeple (which is set)
        print(f"Thanks for taking our poll {people}")

You cannot check all people such way, you should check person one by one, so it would look that way你不能这样检查所有人,你应该一个个检查一个人,所以看起来是这样的

for person in people: # we iterate over all peoples one by one
    if person in favorite_languages:
        print(f"Thanks for taking our poll {person}")


  [1]: https://stackoverflow.com/questions/14535730/what-does-hashable-mean-in-python

In this solution, I added the names common to both arrays to a list named poll_takers.在这个解决方案中,我将 arrays 的共同名称添加到名为 poll_takers 的列表中。 This way, you only get those names printed in the end.这样,您最终只会打印出这些名称。

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil':  'python'
}
people = {'ryker', 'trey', 'jen', 'edward'}
poll_takers = []

for p in people:
    for keys in favorite_languages:
        if p in keys:
            poll_takers.append(p)
            print((f"Thanks for taking our poll {' '.join(poll_takers)}."))

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

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