python - 如何在线性时间内根据键重新组合列表列表?

标签 python list loops anagram

嗨,我是 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/

相关文章:

python - 在不使用 for 循环的情况下将值应用于 DataFrame

python - 类型错误 : count() takes at least 1 argument (0 given)

python - 删除 Python 中连续部分重复的元素

Python : List of dict, 如果存在则增加一个字典值,如果不附加一个新字典

sql - 如何根据参数对 x 个表列求和?

python - 尽管 python selenium 中的文档可用,但元素不可见

python - 相同值的饼图标签重叠。

python - 如何从 Python 脚本向 Google App Script API 传递参数?

python - 缺少 "from typing import List"- 脚本错误,但函数中没有

c - 将指针元素赋值给数组中的另一个指针元素是什么意思?