【问题标题】:Mapping values from for-loop lines to a list of tuples?将值从for循环行映射到元组列表?
【发布时间】:2017-04-03 12:07:04
【问题描述】:

对于以下代码,我试图打印出基于列标题从行映射到它的元组列表中的值。但是,映射似乎出错了,并没有给我想要的值。

import itertools as it

def buc(column_headers, tuples):
    row_dict = {}   
    attribs = [1,2]
    measure = 10

    # generate binary table based on number of columns
    binaries = [i for i in it.product(range(2), repeat=(len(attribs)))]

    for line in binaries:
        line = list(line)

        # replace binary of 1 with 'ALL' or 0 with value from input attribs
        for index, item in enumerate(line):
            if (item == 1):
                line[index] = 'ALL'
            elif (item == 0):
                line[index] = attribs[index]

        line.append(measure)
        print(line)

        # map column values to column heading by index and store in row_dict (e.g. {'A': 1, 'B': 'ALL', 'M': 100} )
        for i in range(len(line)):
            row_dict[column_headers[i]] = line[i]
        tuples.append(row_dict)

    print(tuples)

以下是我得到的当前输出:

>>> buc(['A', 'B', 'M'], [])
[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
[{'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}]

我想要的正确输出应该是以下,其中根据列标题的索引将行正确映射到元组:

>>> buc(['A', 'B', 'M'], [])
[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
[{'A': '1', 'B': '2', 'M': 10}, {'A': '1', 'B': 'ALL', 'M': 10}, {'A': 'ALL', 'B': '2', 'M': 10}, {'A': 'ALL', 'B': 'ALL', 'M': 10}]

我哪里做错了?

【问题讨论】:

    标签: python mapping


    【解决方案1】:

    发生这种情况是因为您的列表 tuples 仅包含对原始字典的引用。见this answer。你可以通过copying 字典来解决这个问题。

    替换

    tuples.append(row_dict)
    

    tuples.append(row_dict.copy())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2016-07-31
      • 2015-04-30
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      相关资源
      最近更新 更多