Python 集、键和字典

Python Sets, Keys, and Dictionaries

我想做的是询问用户姓名,然后使用集合和密钥找出一个人在多少个俱乐部中。我对字典和集合还是陌生的,所以我对如何去做这件事有点困惑。到目前为止,我有这个,但它不起作用并给我一个错误:

clubs = {'WSA': set(['Maria', 'Kennedy']), 'Reds': set(['Simon', 'Yamamoto']), 'Hikes': set(['Maria']), 'UVD': set(['Silver', 'Hasamov']) }

def member():
    name = raw_input('Name ==> ')
    i = 0
    memset = set([])
    nomemset = set([])
    while i <= len(clubs.keys()):
        for club in clubs:
            if clubs[clubs.keys()[i]][i] == clubs[clubs.keys()[i+1]][i]:
                memset.add(clubs.keys()[i])
                memset.add(clubs.keys()[i+1])
            else:
                nomemset.add(clubs.keys()[i])
                nomemset.add(clubs.keys()[i+1])
    print 'Member of: ', memset
    print 'Not member of: ', nomemset

member()

示例输出如下:

Name ==> Maria
Member of: set(['WSA', 'Hikes'])
Not member of: set(['Reds', 'UVD'])

感谢任何帮助!

你让事情变得比现在更困难。使用

for key in dict

迭代密钥,dict[key]获取密钥。 此外,要知道某些 value 是否在 set 中,请使用 if value in set 语法。然后,你的代码会变得更简单:

clubs = {'WSA': set(['Maria', 'Kennedy']), 'Reds': set(['Simon', 'Yamamoto']), 'Hikes': set(['Maria']), 'UVD': set(['Silver', 'Hasamov']) }

def member():
    name = raw_input('Name ==> ')
    i = 0
    memset = set() #As recommended by TigerhawkT3
    nomemset = set()
    for (club, members) in clubs.items(): #As recommended by @DeGlopper
        if name in members:
           memset.add(club)
        else:
           nomemset.add(club)
    print 'Member of: ', memset
    print 'Not member of: ', nomemset

member()