【问题标题】:Creating dict from all possible combinations of 2 separate lists从 2 个单独列表的所有可能组合中创建 dict
【发布时间】:2011-09-12 19:20:12
【问题描述】:

我在互联网的一系列电子管中发现了这段有用的代码:

x=[1,2,3,4]
y=[1,2,3,4]
combos=[(`i`+`n`) for i in x for n in y]
combos
['11','12','13','14','21','22','23','24','31','32','33','34','41','42','43','44']

我正在尝试做的事情如下:

combinations={(i: `n`+`d`) for i in range(16) for n in x for d in y}
combinations
{1: '11', 2: '12', 3: '13', 4: '14', 5: '21', 6: '22'...etc}

但显然这是行不通的。这可以做到吗?如果有,怎么做?

【问题讨论】:

  • 你希望字典键是什么?
  • 如果可能,只使用指定范围内的数字。
  • 请注意,(1) 反引号作为 repr 的快捷方式在 3.x 中被删除,即使在 2.x 中也可以说是一个坏主意,(2) itertools 模块对此进行了概括和几个相关的算法。另外,如果键是连续的整数,为什么要使用字典?这就是列表的用途。
  • 好吧,因为我试图从这个字典生成对象,其名称变量为 'x'+'y' 和另外两个变量分别存储 x 和 y:for i in adict: alist.append(object(i, int(adict[i][0]), int(adict[i][1])))

标签: python python-2.x


【解决方案1】:
combos = [str(i) + str(n) for i in x for n in y] # or `i`+`n`, () for a generator
combinations = dict((i+1,c) for i,c in enumerate(combos))
# Only in Python 2.6 and newer:
combinations = dict(enumerate(combos, 1))
# Only in Python 2.7 and newer:
combinations = {i+1:c for i,c in enumerate(combos)}

【讨论】:

  • 请注意,这将从 0 处的键开始,而不是从 1 开始(我相信有一个关键字参数可以改变它)并且可以使用生成器表达式保存一个大的中间列表。
  • 哇,我觉得自己很笨。谢谢菲尔哈克! Stackoverflow 再次进行救援。 :)
  • @delnan 已修复并更新为使用 enumerate 的 start 参数的更好版本。
【解决方案2】:

从你的第一个例子开始:

x=[1,2,3,4]
y=[1,2,3,4]
combos=[(`i`+`n`) for i in x for n in y]

然后添加:

combinations = {i: c for i, c in enumerate(combos)}

【讨论】:

    【解决方案3】:

    你……可能……不想那样。至少,我可以看到没有一个很好的理由需要它。如果您所追求的是能够跟踪他们的位置,您希望结果是一个列表,它已经是。如果你需要知道索引,你应该这样做:

    for idx, combo in enumerate(combinations):
      print idx+1, combo
    

    如果您确实需要通过位置(和列表索引 + 1)访问它们,您可以执行以下操作:

    lookup = dict((idx+1, combo) for idx, combo in enumerate(combinations))
    

    【讨论】:

      【解决方案4】:

      另外,itertools 模块中有一个product 函数可以在这里使用

      from itertools import product
      x=[1,2,3,4]
      y=[1,2,3,4]
      
      combs = {i+1: ''.join(map(str,p)) for i,p in enumerate(product(x,y))}
      

      ''.join(map(str,p)) 是将p(即int-stuple)的所有项目转换为str 然后使用''.join(...) 加入它们的代码。如果您不需要此代码,请留下 p 而不是此代码。

      另外,请注意,{j for j in js} 语法仅适用于 Python 2.7

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多