gpt4 book ai didi

python - 从嵌套列表中删除相似元素

转载 作者:行者123 更新时间:2023-12-01 06:25:35 24 4
gpt4 key购买 nike

我使用以下代码创建嵌套列表:

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]]

最佳答案

与其删除相似的,不如从一开始就不要生成它们。实际上,您不需要组合,您需要重叠的 block (包含多个奇怪项目的 block 除外,您的代码已经考虑到了这一点,我在这里进行了调整)。

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]]

相关:Splitting a Python list into a list of overlapping chunks

关于python - 从嵌套列表中删除相似元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60162736/

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