【问题标题】:How to split a chunk into two chunks in a list based on condition in python?python - 如何根据python中的条件将一个块分成两个块?
【发布时间】:2018-04-08 05:56:29
【问题描述】:

给出的例子

list = [[2, 3, 4], [3,4,5,6,7]]

如果任何块的值大于值 4,我想拆分给定示例列表中的块。

所以输出应该是

[[2, 3, 4], [3,4], [5, 6,7]].

不知怎的,我得到了所需的答案,但是,我只想知道,

“Python”中是否有任何单行语句或函数可以根据给定条件提供所需的输出?

【问题讨论】:

标签: python arraylist


【解决方案1】:

正如 cmets 中的某人所建议的那样,其他方法会更具可读性,但我一直在玩如何用一行代码来做到这一点,只是为了好玩:

list = [[2, 3, 4], [3,4,5,6,7]]
new_list = [a for b in [[[x for x in y if x <= 4], [x for x in y if x > 4]] for y in list] for a in b if a]
print(new_list)

结果: [[2, 3, 4], [3, 4], [5, 6, 7]]

【讨论】:

    【解决方案2】:

    您可能应该使用分块生成器

    def chunks(l, n):
        """Yield successive n-sized chunks from l."""
        for i in range(0, len(l), n):
            yield l[i:i + n]
    

    然后,您可以通过生成器函数提供列表,该生成器函数将在 2 级列表中分块

    def chunk_items(l, n):
        for sub_l in l:
            yield from chunks(sub_l, n)
    

    或者,如果您使用的是 python

    def chunk_items(l, n):
        for sub_l in l:
            for x in chunks(sub_l, n):
                yield x
    

    这些返回一个生成器,但如果你真的想把它变成一个列表。

    new_list = [x for x in chunk_items(lst, 3)]
    

    编辑:

    刚刚在您的问题中看到,如果子列表的长度大于 5,您只想以 3 个为一组进行分块,这是您可以修改分块器的方法。

    def chunk_items(l, n=3, m=5):
        for sub_l in l:
            if len(sub_l) > m:
                yield from chunks(sub_l, n)
            else:
                yield sub_l
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多