Use*_*291 3 python dictionary list python-3.x
xs = [
[1,2,3,4],
[5,6,7,8],
[9,0,0,1],
[2,3],
[0],
[5,8,3,2,5,1],
[6,4],
[1,6,9,9,2,9]
]
""" expected output:
xs_dict = {
1: [[0]]
2: [[2,3],[6,4]]
4: [[1,2,3,4],[5,6,7,8],[9,0,0,1]]
6: [[5,8,3,2,5,1],[1,6,9,9,2,9]]
}
"""
Run Code Online (Sandbox Code Playgroud)
我可以这样做,例如,通过
xs_dict = {}
for x in xs:
aux = xs_dict.get(len(x),[])
aux.append(x)
xs_dict[len(x)] = aux
print(xs_dict)
Run Code Online (Sandbox Code Playgroud)
但我不禁觉得应该有更多的pythonic方法来实现这一目标.
它是什么?
from itertools import groupby
xs_dict = {
key: list(value)
for (key, value) in groupby(sorted(xs, key=len), len)
}
Run Code Online (Sandbox Code Playgroud)
正如下面的评论中所讨论的那样,输入的必要分类是一个不必要的代价.对于大输入,这将使这种算法的速度超过必要的速度.考虑使用@hiroprotagonist的解决方案,或者替换可以处理未排序输入的groupby(sorted(…), …)by groupby().
你可以使用defaultdict:
from collections import defaultdict
xs_dict = defaultdict(list)
for item in xs:
xs_dict[len(item)].append(item)
Run Code Online (Sandbox Code Playgroud)
python dicts也有一个很好的方法调用setdefault(这样你不需要导入任何东西):
xs_dict = {}
for item in xs:
xs_dict.setdefault(len(item), []).append(item)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |