嗨,我是 Python 新手,我有一个列表列表
arr=[['act', 'abd'], ['cat', 'act'], ['tac', 'act'], ['bad', 'act'], ['fad' , 'adf']]
我想使用 arr[index][1] (在本例中为“act”、“abd”和“adf”)作为重新组合列表列表的键,使其在 O(N) 中变成这样N 为输入列表的时间:
arr=[['act','act','cat','tac'],['abd','bad'],['adf','fad']]
这是我尝试过的,但输出没有意义:
def groupList(a_list):
index=0
searchList=[]
while index<len(tempList)-1:
key=tempList[index][1]
newList=[]
newList.append(key)
newList.append(tempList[index][0])
if tempList[index+1][1]==key:
newList.append(tempList[index+1][0])
else:
searchList.append(newList)
index+=1
print(searchList)
输出为:
[['abd', 'act'], ['act', 'bad']]
任何帮助将不胜感激,谢谢
最佳答案
您可以使用itertools.groupby
对列表列表中的列表进行分组
>>> from itertools import groupby
>>> f = lambda l: l[-1]
>>> [[k]+[l[0] for l in v] for k,v in groupby(sorted(arr, key=f), f)]
[['abd', 'bad'], ['act', 'act', 'cat', 'tac'], ['adf', 'fad']]
关于python - 如何在线性时间内根据键重新组合列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51781908/