英文:
How to group the elements of the same value in a list in a sorted way
问题
如示例所示,如果我们有:
arr = [1, 4, 5, 1, 6, 4, 7, 5]
我该如何分组这些项以使结果为 [1, 1], [4, 4], [5, 5], [6], [7]
?
英文:
For example, if we have:
arr= [1,4,5,1,6,4,7,5]
How can I group the items so the result is [1,1],[4,4],[5,5],[6],[7]
?
答案1
得分: 2
使用 itertools.groupby
函数:
from itertools import groupby
arr = [1, 4, 5, 1, 6, 4, 7, 5]
out = [list(g) for _, g in groupby(sorted(arr))]
输出:[[1, 1], [4, 4], [5, 5], [6], [7]]
但是排序的时间复杂度是 O(n*logn)。
要使用中间字典实现 O(n) 时间复杂度的解决方案:
d = {}
for x in arr:
d.setdefault(x, []).append(x)
out = list(d.values())
注意:这不会对值进行“排序”,只会对它们进行分组。
输出:[[1, 1], [4, 4], [5, 5], [6], [7]]
英文:
Using itertools.groupby
:
from itertools import groupby
arr= [1,4,5,1,6,4,7,5]
out = [list(g) for _, g in groupby(sorted(arr))]
Output: [[1, 1], [4, 4], [5, 5], [6], [7]]
But sorting is O(n*logn).
For an O(n) solution using an intermediate dictionary:
d = {}
for x in arr:
d.setdefault(x, []).append(x)
out = list(d.values())
NB. this doesn't "sort" the values here, only groups them.
Output: [[1, 1], [4, 4], [5, 5], [6], [7]]
答案2
得分: 1
你也可以使用 Counter
从 collections 模块中
from collections import Counter
arr = [1, 4, 5, 1, 6, 4, 7, 5]
counts = Counter(arr)
group = [[item] * count for item, count in counts.items()]
print(group)
[[1, 1], [4, 4], [5, 5], [6], [7]]
英文:
You could also use Counter
from collections
from collections import Counter
arr= [1,4,5,1,6,4,7,5]
counts = Counter(arr)
group = [[item] * count for item, count, in counts.items()]
print(group)
[[1, 1], [4, 4], [5, 5], [6], [7]]
答案3
得分: 0
你可以使用字典来汇总值,然后将其值转换为列表:
arr = [1, 4, 5, 1, 6, 4, 7, 5]
D = dict()
D.update((n, D.get(n, []) + [n]) for n in arr)
result = list(D.values()) # 或者如果需要可以使用sorted(D.values())
print(result) # [[1, 1], [4, 4], [5, 5], [6], [7]]
这将保留每个不同值首次出现的原始顺序(在你的示例中,这些值已经按升序排列)。如果第一次出现的值未排序,您可以随后对结果进行排序或者在已排序的列表上使用groupby
方法:
from itertools import groupby
result = [g for _, [*g, ] in groupby(sorted(arr))]
print(result) # [[1, 1], [4, 4], [5, 5], [6], [7]]
英文:
You can use a dictionary to aggregate the values and then convert its values to a list:
arr= [1,4,5,1,6,4,7,5]
D = dict()
D.update( (n,D.get(n,[])+[n]) for n in arr )
result = list(D.values()) # or sorted(D.values()) if needed
print(result) # [[1, 1], [4, 4], [5, 5], [6], [7]]
This will preserve the original order of first appearance of each distinct value (which happens to already be in ascending order of value as well in your example). If the first occurrences are not sorted you can sort the result afterward or use the groupby method on the sorted list:
from itertools import groupby
result = [ g for _,[*g,] in groupby(sorted(arr)) ]
print(result) # [[1, 1], [4, 4], [5, 5], [6], [7]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论