在不解压 intertool 对象的情况下索引 itertools 排列

问题描述 投票:0回答:1

我有以下内容

from itertools import islice, permutations

# Function to get a chunk of the itertools object
def get_chunk(iterator, chunk_size):
    return list(islice(iterator, chunk_size))

# Example usage
sequence = [1, 2, 3, 4]
chunk_size = 10  # Define your chunk size here
permutations_iterator = permutations(sequence)
chunk = get_chunk(permutations_iterator, chunk_size)

# Assuming the chunk has at least two elements
if len(chunk) > 1:
    first_element = chunk[0]
    last_element = chunk[-1]
elif len(chunk) == 1:
    first_element = last_element = chunk[0]
else:
    first_element = last_element = None

print("First element of the chunk:", first_element)
print("Last element of the chunk:", last_element)

我想获得每个块的第一个和最后一个排列,而不将它们解压到列表中以避免内存问题。有办法吗?

我想获取排列列表,其中对于每个块,我都有 itertool 对象的第一个和最后一个排列,而不必解压 itertool 对象。

permutation python-itertools
1个回答
0
投票

可以直接计算特定 n 值的第

n
排列,而无需计算所有中间排列。

这是在more_itertools库的函数nth_permutation中实现的。

from more_itertools import nth_permutation
from math import factorial

sequence = [1,2,3,4]
chunk_size = 10

number_of_permutations = factorial(len(sequence))

print(*(
    (nth_permutation(sequence, len(sequence), i), nth_permutation(sequence, len(sequence), min(i+chunk_size-1, number_of_permutations-1)))
    for i in range(0, number_of_permutations, chunk_size)
),sep='\n')
# ((1, 2, 3, 4), (2, 3, 4, 1))
# ((2, 4, 1, 3), (4, 1, 3, 2))
# ((4, 2, 1, 3), (4, 3, 2, 1))
© www.soinside.com 2019 - 2024. All rights reserved.