0
對於下面的代碼,我試圖根據列標題列出從行映射到它的元組列表中的值。然而,映射似乎出錯了,並沒有給我我想要的值。將for循環行的值映射到元組列表?
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}]
我哪裏錯了?
啊!難怪!好的謝謝! – iteong