我正在使用以下代码创建嵌套列表:
from itertools import combinations
def get_nested_list(arr, n, k):
iterator = 0
nest = []
for i in range(1, n):
for combo in combinations(arr, i):
odd_num = 0
for item in combo:
if item % 2 != 0:
odd_num += 1
if odd_num <= k:
iterator += 1
nest.append(combo)
nest = [list(i) for i in nest]
return nest
a = [1, 2, 3, 4]
b = len(a)
c = 1
print(get_nested_list(a, b, c))
这是我的输出:
[[1], [2], [3], [4], [1, 2], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 4], [2, 3, 4]]
但是,我得到了像[1,2]
和[1,4]
这样的元素,它们具有相同的x值,[2, 4]
并且[3, 4]
具有相同的y值。如何创建包含完全不同的子列表的列表?这是我要完成的工作:
[[1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [2, 3, 4]]
除了删除相似的内容外,不要一开始就麻烦它们。确实,您不需要组合,而是需要重叠的块(除了包含多个奇数项的块(您的代码已经解释了这些,我在这里进行了修改))。
def overlapping_chunks(size, sequence):
"""Yield overlapping chunks of sequence."""
for i in range(len(sequence)-size+1):
yield sequence[i:i+size]
def powerchunk(sequence):
"""Yield all overlapping chunks of sequence, similar to a powerset."""
for size in range(1, len(sequence)+1):
yield from overlapping_chunks(size, sequence)
a = [1, 2, 3, 4]
max_odds = 1
result = [
chunk for chunk in powerchunk(a)
if sum(item % 2 != 0 for item in chunk) <= max_odds
]
print(result) # -> [[1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [2, 3, 4]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句