Skip to main content
 首页 » 编程设计

python之如何创建一个迭代列表,其中一些变量是独立的,一些是相关的

2024年12月31日8myhome

我正在尝试制作一个排列列表,其中顺序在前两个变量和最后两个变量之间很重要,但在这两个组之间并不重要。我已经能够得到这样的东西:

>>>[p for p in itertools.product([1, 2],[1, 2],[5, 6], [5, 6])] 
 
   [(1, 1, 5, 5), (1, 1, 5, 6), (1, 1, 6, 5), (1, 1, 6, 6), (1, 2, 5, 5), 
    (1, 2, 5, 6), (1, 2, 6, 5), (1, 2, 6, 6), (2, 1, 5, 5), (2, 1, 5, 6),  
    (2, 1, 6, 5), (2, 1, 6, 6), (2, 2, 5, 5), (2, 2, 5, 6), (2, 2, 6, 5),  
    (2, 2, 6, 6)] 

我想得到一些没有重复切换顺序但保留重复变量的东西,如下所示:

   [(1, 1, 5, 5), (1, 1, 5, 6), (1, 1, 6, 6), (1, 2, 5, 5),(1, 2, 5, 6),  
    (1, 2, 6, 6), (2, 2, 5, 5), (2, 2, 5, 6), (2, 2, 6, 6)] 

似乎应该有一种直接的方法来做到这一点,我只是还没有想出它(我主要用 R 编写代码,并且刚刚开始研究 Python 3)。

请您参考如下方法:

比使用 set 来唯一化 product 的结果更好,您可以结合使用 product 和 itertools.combinations_with_replacement直接产生您关心的结果:

from itertools import product, combinations_with_replacement as comb_repl 
 
[p1 + p2 for p1, p2 in product(comb_repl([1, 2], 2), comb_repl([5, 6], 2))] 

这会产生所需的精确输出,没有重复(因此不需要单独的重复数据删除步骤)。

请注意,对于传递给 product 的第一个 iterable,product 将缓存 iterable,因此在这种情况下, 的完整输出comb_repl([5, 6], 2) 将最终存储在内存中,以及您真正想要的所有四 tuple。在这种情况下这很好,但如果您的组合集明显更大,您可能更愿意随时重新计算组合,因此您只需为最终结果支付内存,而不是完整的 combinations_with_replacement 集第二个迭代器的输出。由于 product 缓存,您必须避免它,使用重复创建第二个 combinations_with_replacement 迭代器的多 for 列表理解:

# Also switched argument to second comb_repl to a tuple, so argument is not repeatedly rebuilt; 
# slightly less readable due to profusion of parens, but equivalent behavior 
[p1 + p2 for p1 in comb_repl([1, 2], 2) for p2 in comb_repl((5, 6), 2)] 

在测试中,当内存不是问题时,嵌套循环 listcomp 比使用 product 稍慢(product 将更多工作推给 C 层,并且只创建combinations_with_replacement 的两个实例,而不是第一个迭代器的每个输出加一;在第二遍和后续遍历中,它迭代输出的缓存 tuple,速度与Python 获取),因此如果您知道您的参数不会变得足够大以致 product 缓存变得重要,那么使用 product 可以获得最佳性能。

在所有情况下,除非您真的需要一个已实现的列表,否则最好使用生成器表达式 (genexpr),因为 genexpr 仅在被询问时产生结果,并且不必将它们全部存储在内存中;你可以循环一次,然后它就用完了,但在很多情况下,你只需要循环一次就可以了。使用 genexpr,用法如下:

# Outer square brackets changed to parentheses 
products = (p1 + p2 for p1 in comb_repl([1, 2], 2) for p2 in comb_repl((5, 6), 2)) 
for p in products: 
    ... do stuff with one output ... 

不再复杂,并且对于更大的组合,不会耗尽内存。