简体   繁体   中英

Mapping values from for-loop lines to a list of tuples?

For the following code, I'm trying to print out the values within a list of tuples that are mapped from the line to it based on column headers. However, the mapping seems to go awry and do not give me the values I want.

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)

The following is the current output I get:

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

The correct output I want should be the following, where the lines is mapped to the tuples correctly, based on index of the column headings:

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

Where have I done wrong?

This happens because your list tuples only contains a reference to the original dictionary. See this answer . You can fix this by copying the dictionary.

Replace

tuples.append(row_dict)

with

tuples.append(row_dict.copy())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM