gpt4 book ai didi

python - 如何重新排列这样的列表(python)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:03:37 26 4
gpt4 key购买 nike

例如,列表 to_be 包含:3 个 "a",4 个 "b",3 个 "c", 5 个 "d"...

to_be = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "d", "d", "d", "d", "d", ...]

现在我希望它是这样的:

done = ["a", "b", "c", "d", ... , "a", "b", "c", "d", ... , "b", "d", ...] (notice: some items are more than others as in amounts, but they need to be still in a pre-defined order, alphabetically for example)

最快的方法是什么?

最佳答案

假设我理解你想要什么,可以通过组合 itertools.zip_longest 相对容易地完成。 , itertools.groupbyitertools.chain.from_iterable() :

我们首先将项目分组(“a”“b” 等...),然后将它们压缩以获取它们按照您想要的顺序(每组一个),使用 chain 生成单个列表,然后删除压缩引入的 None 值。

>>> [item for item in itertools.chain.from_iterable(itertools.zip_longest(*[list(x) for _, x in itertools.groupby(to_be)])) if item]
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'b', 'd', 'd']

您可能想要分离出一些 list comprehensions但是,为了使其更具可读性:

>>> groups = itertools.zip_longest(*[list(x) for _, x in itertools.groupby(to_be)])
>>> [item for item in itertools.chain.from_iterable(groups) if item]
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'b', 'd', 'd']

(给定版本适用于 3.x,对于 2.x,您需要 izip_longest()。)

与往常一样,如果您期望空字符串、0 等...那么您将想要执行 if item is not None,并且如果您需要保留 None 机智的值(value)观,创建一个哨兵对象并检查其身份。

你也可以使用 the roundrobin() recipe在文档中给出,作为压缩的替代方法,这使得它变得非常简单:

>>> list(roundrobin(*[list(x) for _, x in itertools.groupby(to_be)]))
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'b', 'd', 'd']

最后一点,细心的人可能会注意到我从 groupby() 生成器制作列表,这看起来很浪费,原因来自 the docs :

The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list.

关于python - 如何重新排列这样的列表(python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13391334/

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