【问题标题】:Basic Python dictionary基本 Python 字典
【发布时间】:2015-01-19 11:16:21
【问题描述】:

我刚刚开始学习一点 Python。我正在使用一些基本的词典。我有一本字典,我复印了。然后我拿另一本字典并从我的副本中取出值:

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

这给我留下了一本包含一些零值的字典。我想要的是一种在它们等于零时从字典中删除项目的方法。

我找到了this previous thread here;似乎这曾经在以前的版本上工作过,但我不明白解决方法。

【问题讨论】:

  • 您遇到的具体问题是什么?您想遍历字典,删除值等于 0 的键;你在哪里尝试实现它,它出了什么问题?

标签: python dictionary


【解决方案1】:

字典实际上可以有零值,如果您想删除它们,只需在您的算法中执行即可。

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

【讨论】:

    【解决方案2】:

    你需要的是理解。它存在于集合、列表和字典中。

    如您所见here,您可以迭代您的集合成员,并仅选择您需要的成员。该命令的输出是选择的那些,您可以将其用作您的副本。

    从该页面复制/粘贴,您有:

    >>> 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}
    {'barry@zope.com'   : 1, 'barry@python.org' : 1, 'guido@python.org' : 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}
    

    您可以阅读其他理解(list 和 set)here。

    现在,在你的情况下,这是一个最小的例子:

    >>> 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}
    

    【讨论】:

      猜你喜欢
      • 2013-01-06
      • 2012-10-18
      • 2023-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2016-06-15
      相关资源
      最近更新 更多