简体   繁体   English

Python序列子列表按特定顺序生成-IterTools?

[英]Python sequences sublist generation in specific order - itertools?

I would like to generate sublists in a specific way and a specific order. 我想以特定的方式和顺序生成子列表。

The idea of the algorithm is the following : 该算法的思想如下:

  • Outer loop: remove the before last item 外循环:删除之前的最后一项
  • Inner loop: remove the first item 内循环:删除第一项

Here's an example starting with the [A, B, C ,D] list : 这是一个以[A, B, C ,D]列表开头的示例:

[A, B, C, D]
[B, C, D] (remove first item)
[C, D]  (remove first item)
[A, B, D]  (remove before last item)
[B, D]  (remove first item)
[A, D]  (remove before last item)
[D] (remove before last item)

The only constraint I have is that the the sublist of length one containing the last item alone have to be last the sublist generated. 我唯一的约束是,仅包含最后一项的长度为1的子列表必须是最后生成的子列表。

I do not have any difficulties to implent this algorithm in a naive iterative way. 我没有任何困难以天真的迭代方式来实现该算法。 But I'd strongly prefer to do it in a more pythonic way, like with list comprehensions or maybe the itertools lib. 但是,我强烈希望以一种更加Python化的方式来执行此操作,例如使用列表解析或itertools库。

Any advice please ? 有什么建议吗?

Can be accomplished with a double nested comprehension + some index math: 可以使用双重嵌套理解+一些索引数学来完成:

>>> data = ['A', 'B', 'C', 'D']
>>>
>>> [data[i:j-1]+[data[-1]] for j in range(len(data),0,-1) for i in range(0, j-1)] + [data[-1]]
[['A', 'B', 'C', 'D'], ['B', 'C', 'D'], ['C', 'D'], ['A', 'B', 'D'], ['B', 'D'], ['A', 'D'], ['D']]

The last element is a special case because the sub-list whose combinations are prepended to it is empty, ie the length of the list slice decreases in the following fashion: 最后一个元素是一种特殊情况,因为其组合之前的子列表为空,即列表切片的长度以以下方式减小:

3 2 1
2 1
1
0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM