Basic Python dictionary
我刚开始学一点Python。我在编一些基本词典。我有一本字典,我把它复印一份。然后我拿另一本字典,并从我的副本中去掉这些值:
1 2 3 4 5 6 7 8 9 | teams_goals = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':2} print teams_goals test_teams = {'chelsea' : 1, 'man u' : 1,'Arsenal':1} teams_goals_copy = teams_goals.copy() for team in test_teams: for j in range(test_teams[team]): teams_goals_copy[team]= teams_goals_copy[team]- 1 print teams_goals_copy |
这就给我留下了一本零值字典。我想要的是当字典中的项等于零时从字典中删除这些项的方法。
我在这里找到了前一个线程;似乎这以前用于前一个版本,但我不理解解决方法。
实际上,字典可以有零值,如果您想删除它们,只需在您的算法中执行即可。
1 2 3 4 5 6 7 8 9 10 11 | teams_goals = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':2} print teams_goals test_teams = {'chelsea' : 1, 'man u' : 1,'Arsenal':1} teams_goals_copy = teams_goals.copy() for team in test_teams: for j in range(test_teams[team]): teams_goals_copy[team]= teams_goals_copy[team]- 1 if teams_goals_copy[team] == 0: del(teams_goals_copy[team]) print teams_goals_copy |
你需要的是理解。它存在于集合、列表和字典中。
正如您在这里看到的,您可以迭代集合的成员,并且只选择您需要的成员。命令的输出是选定的,您可以将其用作副本。
从该页复制/粘贴,您有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | >>> print {i : chr(65+i) for i in range(4)} {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} >>> print {k : v for k, v in someDict.iteritems()} == someDict.copy() 1 >>> print {x.lower() : 1 for x in list_of_email_addrs} {'[email protected]' : 1, '[email protected]' : 1, '[email protected]' : 1} >>> def invert(d): ... return {v : k for k, v in d.iteritems()} ... >>> d = {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} >>> print invert(d) {'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3} >>> {(k, v): k+v for k in range(4) for v in range(4)} ... {(3, 3): 6, (3, 2): 5, (3, 1): 4, (0, 1): 1, (2, 1): 3, (0, 2): 2, (3, 0): 3, (0, 3): 3, (1, 1): 2, (1, 0): 1, (0, 0): 0, (1, 2): 3, (2, 0): 2, (1, 3): 4, (2, 2): 4, ( 2, 3): 5} |
你可以在这里读到其他的理解(
现在,在您的例子中,有一个很小的例子:
1 2 3 4 5 6 | >>> my_dict = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':0} >>> print(my_dict) {'man u': 3, 'Man city': 0, 'Arsenal': 1, 'chelsea': 2} >>> second_dict = {x:y for x,y in my_dict.items() if y > 0} >>> print(second_dict) {'man u': 3, 'Arsenal': 1, 'chelsea': 2} |