我有一个循环的函数,并打印许多任意数量的单独列表。
示例:
编辑:这是我运行我的功能时得到的输出。
['Hello', 'Mello', 'Jello']
['Sun', 'Fun', 'Run']
['Here', 'There', 'Everywhere'}
现在我想将这些任意单独的列表转换为这样的字典:
{'Hello':['Sun','Here'], 'Mello':['Fun', 'There'], 'Jello':['Run', 'Everywhere']}
第一个列表中的每个元素都成为“键”,而下面的所有元素都成为“值”(或者它是否相反?)...
我尝试的是:
{k:v for k, *v in zip(*data)}
但是当我这样做时,我会得到类似这样的输出:
{'1': ('T', 'P', '2'), '7': ('a', '.', '6'), '9': ('t', 'r', '8')}
{'0': ('h', 'L', '1'), '2': ('T', 'N', '1')}
{'0': ('o', 'V', '0'), '2': ('T', 'B', '1')}
答案 0 :(得分:3)
>>> L1 = ['Hello', 'Mello', 'Jello']
>>> L2 = ['Sun', 'Fun', 'Run']
>>> L3 = ['Here', 'There', 'Everywhere']
>>> {k:v for k, *v in zip(L1, L2, L3)}
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}
我不清楚你在data
中有什么,但这很好用
>>> data = [L1, L2, L3]
>>> {k:v for k, *v in zip(*data)}
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}
其他选项
>>> dict(map(lambda k, *v:(k, v), *data))
{'Hello': ('Sun', 'Here'), 'Mello': ('Fun', 'There'), 'Jello': ('Run', 'Everywhere')}
>>> dict(map(lambda k, *v:(k, list(v)), *data))
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}
答案 1 :(得分:0)
你可以做的一件事是这样的:
myLists = [ #lists you want to convert
['Hello', 'Mello', 'Jello']
['Sun', 'Fun', 'Run']
['Here', 'There', 'Everywhere']
]
theDict = {} #where you will store the converted lists
for list in myLists: #for each list...
theDict[list[0]] = list[1:] #set the dict's key to list[0] and contents to everything starting from index 1