Python列表结构修改

标签 python list

转换以下内容的最佳方法是什么:

myList = [
          ['ItemB','ItemZ'],
          ['ItemB','ItemP'],
          ['ItemB','ItemJ','Item6'],
          ['ItemB','ItemJ','Item5']
         ]

Python 中的这个:

newList = ['ItemB',['ItemP','ItemZ',['ItemJ',['Item5','Item6']]]]

我能够使用按 Len 排序的递归函数接近,但无法找到按 Len 按字母顺序排序的好方法。任何帮助将不胜感激!

最佳答案

也许不是最优雅的方式,但这似乎有效:

首先,我们使用 defaultdictsdefaultdictsdefaultdictsdefaultdict 将列表列表转换为字典,又名 infinitedict

myList = [['ItemB','ItemZ'],['ItemB','ItemP'],['ItemB','ItemJ','Item6'],['ItemB','ItemJ','Item5']]

from collections import defaultdict
infinitedict = lambda: defaultdict(infinitedict)
dictionary = infinitedict()
for item in myList:
    d = dictionary
    for i in item:
        d = d[i]

现在,我们可以使用递归函数将该字典转换回树形列表:

def to_list(d):
    lst = []
    for i in d:
        lst.append(i)
        if d[i]:
            lst.append(to_list(d[i]))
    return lst

输出与您的预期输出有点不同,但这对我来说似乎更有意义:

>>> print(to_list(dictionary))
['ItemB', ['ItemZ', 'ItemJ', ['Item6', 'Item5'], 'ItemP']]

或者,更接近您的预期结果(但仍然不完全相同,因为由于字典的中间步骤,顺序被打乱),改为使用以下内容:

def to_list(d):
    return [[i] + [to_list(d[i])] if d[i] else i for i in d]

输出:

>>> print(to_list(dictionary)[0])
['ItemB', ['ItemZ', ['ItemJ', ['Item6', 'Item5']], 'ItemP']]

关于Python列表结构修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17756187/

相关文章:

python - 无法弄清楚如何使用表达式在 Python 中验证加拿大邮政编码

python - 如何更改 iterrows() 的起始索引?

python - 绘制两个不同颜色的列表

c - c 中的链接结构

java - java中如何返回一张表的数据的数组列表?

python - 使用 Qutip 和 slepc4py 在 HPC 上快速寻找特征向量

python - 在 pandas.DataFrame 的对角线上设置值

Python2.7 : ssh. exec_command 没有执行任何命令

使用 List<int[]>.add() 重复值的 Java 递归

python - 连接两个长度不同的列表中的元素