更新时间:2023-02-23 09:47:26
您不能将 list
作为键,但可以使用 tuple
。另外,您不需要在列表上切片,而在子列表上。
You can't have list
as key, but tuple
is possible. Also you don't need to slice on your list, but on the sublist.
您需要前两个值 sublist [:2]
作为键,对应的值是索引2 sublist [2:]
You need the 2 first values sublist[:2]
as key and the corresponding values is the sublist from index 2 sublist[2:]
new_dict = {}
for sublist in li:
new_dict[tuple(sublist[:2])] = tuple(sublist[2:])
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}
与dict理解相同
new_dict = {tuple(sublist[:2]): tuple(sublist[2:]) for sublist in li}
print(new_dict) # {('a', 'b'): ('1', '2'), ('c', 'd'): ('3', '4')}