gpt4 book ai didi

python - 将具有重复项的字符串列表划分为没有本地重复项的不同列表

转载 作者:行者123 更新时间:2023-12-02 18:24:56 24 4
gpt4 key购买 nike

在Python中,如何将字符串列表划分为多个列表,每个列表没有重复项,在每次迭代中获取尽可能多的字符串,直到每个项目都插入到列表中?

输入:

["1", "2", "2", "3", "3", "3", "4", "5" ]

输出:

["1", "2", "3", "4", "5"]
["2", "3"]
["3"]

我怎样才能有效地做到这一点?

最佳答案

这是一个简单的方法,前提是元素可以用作字典键:

def partition(xs):
from collections import Counter
result = []
c = Counter(xs)
while c:
uniq = list(c) # one of each key remaining
result.append(uniq)
c -= Counter(uniq) # and remove one of each of those
return result

然后

>>> xs = ["1", "2", "2", "3", "3", "3", "4", "5"]
>>> partition(xs)
[['1', '2', '3', '4', '5'], ['2', '3'], ['3']]

关于python - 将具有重复项的字符串列表划分为没有本地重复项的不同列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70358490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com