【问题标题】:Why do I get two different dictionaries, if I reverse the order of the zip lists如果我颠倒 zip 列表的顺序,为什么我会得到两个不同的字典
【发布时间】:2017-04-27 13:08:12
【问题描述】:

我对下面的代码有点疑惑:

Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> list_a = ['300', '300', '200', '150', '150', '120', '1']

>>> list_b = ['butter', 'sugar', 'yolks', 'flour', 'potato_starch', 'egg_whites', 'lemon_zest']

>>> c = dict(zip(list_b, list_a))

>>> print c
>>>{'butter': '300', 'lemon_zest': '1', 'flour': '150', 'egg_whites': '120', 'sugar': '300', 'yolks': '200', 'potato_starch': '150'}

>>> c = dict(zip(list_a, list_b))

>>> print c
>>>{'300': 'sugar', '200': 'yolks', '1': 'lemon_zest', '120': 'egg_whites', '150': 'potato_starch'}

为什么通过反转列表,字典“c”会丢失两对“成分:数量”?
我注意到最多 6 双就可以了。
我为不完整的解释道歉,但我不知道如何向我解释这是一个异常。
感谢愿意帮助我理解的人。

【问题讨论】:

  • 字典键必须是唯一的。如果您从 list_a 创建密钥,则它包含重复项,因此您会覆盖针对该密钥存储的任何现有数据。

标签: python python-2.7 list dictionary


【解决方案1】:

颠倒参数的顺序意味着以前的字典值现在将优先作为键。

更重要的是,以前的字典有重复的值(例如 300)。但是,一旦您交换了参数的顺序并且它们成为键,则只有其中一个值将其作为新字典的键;字典不允许重复键。

【讨论】:

  • 谢谢,我明白了
【解决方案2】:

您有多个具有相同编号的项目,因此会覆盖该特定键的值。

{"a":300, "b":300} 将变为 {300:"a", 300:"b"}。由于键必须是唯一的,因此 dict 是通过首先将“a”分配给键 300 来创建的,然后立即被“b”覆盖。

【讨论】:

  • @tobias_k 确切地说:{"a":300, "b":300} 将变为 {300:"a", 300:"b"},这是无效的,因为键必须是唯一的.
  • 谢谢,我明白了
  • @EricDuminil:你是对的,错误的选择。编辑并希望澄清我的观点。谢谢!
【解决方案3】:

查看您的数据结构,您可能对Counter 感兴趣:

from collections import Counter

list_a = ['200', '300', '300', '200', '150', '150', '120', '1']
list_b = ['butter', 'butter', 'sugar', 'yolks', 'flour', 'potato_starch', 'egg_whites', 'lemon_zest']

ingredients = Counter()

for ingredient, quantity in zip(list_b, list_a):
    ingredients[ingredient] += int(quantity)

print(ingredients)
# Counter({'butter': 500, 'sugar': 300, 'yolks': 200, 'flour': 150, 'potato_starch': 150, 'egg_whites': 120, 'lemon_zest': 1})

对于每种成分,当一个键出现多次时(例如,'butter':200 和 300),它将对数量求和,而不是覆盖值。

【讨论】:

  • 好的,谢谢,我不应该有双重成分,但您的集成可能非常有用。
【解决方案4】:
d = dict(zip(list_a, list_b))
    if len(d) != len(list_a):
        d = dict(zip(list_b, list_a))

检查字典的长度,如果不等于两个列表之一的长度,则颠倒'zip'的顺序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多