【问题标题】:Creating a list containing dictionaries whose values are sequentially selected from a different list创建一个包含字典的列表,其值是从不同的列表中顺序选择的
【发布时间】:2019-09-27 02:17:56
【问题描述】:

我正在尝试创建一个字典列表,该列表由相同的键与从不同列表中顺序选择的值配对。

这里的解决方案对我没有帮助: Creating a unique list of dictionaries from a list of dictionaries which contains same keys but different values,

One liner: creating a dictionary from list with indices as keys,

Create dictionary from list python

ids = [8, 9, 10, 11, 12]
field = ['person']
container = []

我得到的最接近的是:

for i in ids:
    container.append(dict(zip(field, [i for i in ids])))

结果:

[{'person': 8}, {'person': 8}, {'person': 8}, {'person': 8}, {'person': 8}]

我需要什么:

[{'person': 8}, {'person': 9}, {'person': 10}, {'person': 11}, {'person': 12}]

【问题讨论】:

  • 如果字段超过 1 个会怎样? {'person': 8, 'foo':8}{person:8}{foo:8}?

标签: python python-3.x


【解决方案1】:

如果你有一个字段,你可以这样做:

for i in ids:
    container.append(dict(zip(field, [i])))

对于多个字段项,您可以执行以下操作:

from itertools import product
for i,j in product(ids, field):
    container.append(dict(zip([i],[j])))

【讨论】:

    【解决方案2】:

    您已经使用 for 循环遍历 ids,您也不需要列表解析。

    而且你不需要zip。它没有做任何有用的事情,因为它总是在到达最短序列的末尾时停止。由于field 只有一个元素,它只使用[i for i in ids] 的第一个元素,这就是为什么你总是得到8

    for i in ids:
        container.append({field[0]: i})
    

    【讨论】:

      【解决方案3】:

      如果field 只有一个元素,而您已经在进行列表理解,为什么还要麻烦zip

      container = [{field[0]: i} for i in ids]
      

      【讨论】:

        【解决方案4】:

        如果id是顺序连续的,(你提到顺序选择的值)你可以使用range,另外如果字段列表只有一个元素,为什么不直接使用字符串。

        那么这是一个简单的单行

        print([{'person': i} for i in range(8, 13)])
        #[{'person': 8}, {'person': 9}, {'person': 10}, {'person': 11}, {'person': 12}]
        

        如果列表中有多个元素,那么您也不需要zip

        fields = ['person', 'animal']
        print([{item: i} for i in range(8, 13) for item in fields])
        #[{'person': 8}, {'animal': 8}, {'person': 9}, {'animal': 9}, {'person': 10}, {'animal': 10}, {'person': 11}, {'animal': 11}, {'person': 12}, {'animal': 12}]
        

        另一种选择是itertools.product

        from itertools import product
        ids = [8, 9, 10, 11, 12]
        field = ['person']
        print([{item[0]: item[1]} for item in product(field, ids)])
        #[{'person': 8}, {'person': 9}, {'person': 10}, {'person': 11}, {'person': 12}]
        
        from itertools import product
        ids = [8, 9, 10, 11, 12]
        field = ['person', 'field']
        print([{item[0]: item[1]} for item in product(field, ids)])
        #[{'person': 8}, {'person': 9}, {'person': 10}, {'person': 11}, {'person': 12}, {'field': 8}, {'field': 9}, {'field': 10}, {'field': 11}, {'field': 12}]
        

        【讨论】:

        • range(8, 14) 上升到 13。
        猜你喜欢
        • 1970-01-01
        • 2015-09-13
        • 2022-01-21
        • 1970-01-01
        • 2021-07-03
        • 2017-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多