2024-04-20 16:16:25 发布
网友
我有两个列表['a', 'b', 'c']和[[1,2,3], [4,5,6]]
['a', 'b', 'c']
[[1,2,3], [4,5,6]]
我期望输出{'a':[1,4], 'b':[2,5], 'c':[3,6]},而不使用for循环。你知道吗
{'a':[1,4], 'b':[2,5], 'c':[3,6]}
没有for循环。你知道吗
list1 = ['a', 'b', 'c'] list2 = [[1,2,3], [4,5,6]] flat = reduce(lambda x,y: x+y,list2) d = {} df = dict(enumerate(flat)) def create_dict(n): position = flat.index(df[n])%len(list1) if list1[position] in d.keys(): d[list1[position]].append(df[n]) else: d[list1[position]] = [df[n]] map( create_dict, df) print d
正如在另一个答案中所说的,你可能应该使用zip。但是,如果您想避免使用其他第三方库,您可以通过在每个元素上调用for循环并手动添加到字典中来手动完成。你知道吗
使用^{}:
>>> l1 = ['a', 'b', 'c'] >>> l2 = [[1,2,3], [4,5,6]] >>> dict(zip(l1, zip(*l2))) # zip(*l2) => [(1, 4), (2, 5), (3, 6)] {'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}
更新
如果要获取字符串列表映射,请使用dict comprehension:
>>> {key:list(value) for key, value in zip(l1, zip(*l2))} {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}
没有for循环。你知道吗
正如在另一个答案中所说的,你可能应该使用zip。但是,如果您想避免使用其他第三方库,您可以通过在每个元素上调用for循环并手动添加到字典中来手动完成。你知道吗
使用^{} :
更新
如果要获取字符串列表映射,请使用dict comprehension:
相关问题 更多 >
编程相关推荐