【问题标题】:sorting lists into lists of lists - Python [duplicate]将列表排序为列表列表 - Python [重复]
【发布时间】:2020-11-01 17:29:45
【问题描述】:

我正在尝试编写一个接收列表的函数。例如:

x = ['a', 'b', 'a', 'b', 'b']

它应该将列表排序为列表列表。例如:

x = [['a','a'], ['b', 'b', 'b']]

为此努力寻找起点。

【问题讨论】:

  • 创建一个字典,其中条目作为键,出现作为键,并填充一个新列表。但是,需要额外的内存。

标签: python list sorting


【解决方案1】:

使用集合中的计数器:

from collections import Counter

x = ["a", "b", "a", "b", "b"]
c = Counter(x)
res = []
for k, v in c.items():
    res.extend([(list(k * int(v)))])
print(res)

返回:

[['a', 'a'], ['b', 'b', 'b']]

多合一,使用列表推导:

print([[k,] * v for k, v in c.items()])

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2019-09-18
    • 2014-10-04
    • 2023-03-20
    • 2017-03-24
    相关资源
    最近更新 更多