1

尝试使用列表中的值创建多键字典,其中字典的键是第一列和第一行值,但空单元格除外。

下面的代码没有返回预期的结果。我还尝试了地图功能和列表理解。

# list data
list_data = [['', '', 'VARIANT1', 'VARIANT2'],
         ['power', 'kW', '12', '20'],
         ['range', 'm', '200', '400'],
         ['colour', '', 'blue', 'yellow']]

# my code
import collections
dict_data = collections.defaultdict()
for row in range(1: len(list_data)):
    for column in range(2: len(list_data[0])):
        dict_data[(list_data[row][0], list_data[0][column])
              ] = list_data[row][column]

# desired output
dict_data = {('power', 'VARIANT1'): '12',
         ('range', 'VARIANT1'): '200',
         ('colour', 'VARIANT1'): 'blue',
         ('power', 'VARIANT2'): '20',
         ('range', 'VARIANT2'): '400',
         ('colour', 'VARIANT2'): 'yellow', }
4

1 回答 1

0

您可以通过字典理解来做到这一点:

list_data = [['', '', 'VARIANT1', 'VARIANT2'],
         ['power', 'kW', '12', '20'],
         ['range', 'm', '200', '400'],
         ['colour','' , 'blue', 'yellow']]


keys = {(x[0], y): x[i]  for x in list_data[1:] for i, y in enumerate(list_data[0]) if i >= 2}

keys_sorted = {k: v for k, v in sorted(keys.items(), key=lambda x: x[0][1])}

输出:

>>> keys
{('power', 'VARIANT1'): '12',
 ('power', 'VARIANT2'): '20',
 ('range', 'VARIANT1'): '200',
 ('range', 'VARIANT2'): '400',
 ('colour', 'VARIANT1'): 'blue',
 ('colour', 'VARIANT2'): 'yellow'}

或排序为您的示例输出:

>>> keys_sorted
{('power', 'VARIANT1'): '12',
 ('range', 'VARIANT1'): '200',
 ('colour', 'VARIANT1'): 'blue',
 ('power', 'VARIANT2'): '20',
 ('range', 'VARIANT2'): '400',
 ('colour', 'VARIANT2'): 'yellow'}
于 2019-11-21T11:54:53.620 回答