复制迭代器并生成无序自笛产品 [英] copying iterators and producing unordered self-cartesian product
问题描述
假设我有一个列表,我想生成所有唯一元素对的列表,而不考虑订单。一种方法是:
Say I have a list, and I want to produce a list of all unique pairs of elements without considering the order. One way to do this is:
mylist = ['W','X','Y','Z']
for i in xrange(len(mylist)):
for j in xrange(i+1,len(mylist)):
print mylist[i],mylist[j]
W X
W Y
W Z
X Y
X Z
Y Z
我想用迭代器做这个,我想到了以下内容,即使它没有简洁:
I want to do this with iterators, I thought of the following, even though it doesn't have brevity:
import copy
it1 = iter(mylist)
for a in it1:
it2 = copy.copy(it1)
for b in it2:
print a,b
但这甚至不起作用。什么是更加pythonic和有效的方式,使用迭代器或zip等等?
But this doesn't even work. What is a more pythonic and efficient way of doing this, with iterators or zip, etc.?
推荐答案
这已经完成并且从Python 2.6开始包含在标准库中:
This has already been done and is included in the standard library as of Python 2.6:
import itertools
mylist = ['W', 'X', 'Y', 'Z']
for pair in itertools.combinations(mylist, 2):
print pair # pair is a tuple of 2 elements
对我来说好像是Pythonic; - )
Seems pretty Pythonic to me ;-)
请注意,即使是如果你计算了很多组合,那么组合()
函数会返回一个迭代器,以便你可以立即开始打印它们。请参阅文档。
Note that even if you're calculating a lot of combinations, the combinations()
function returns an iterator so that you can start printing them right away. See the docs.
此外,您将结果称为列表与其自身之间的笛卡尔积,但这并非严格正确:笛卡尔积将具有16个元素(4x4)。您的输出是其中的一部分,即只有2个元素的组合(不允许重复)列表的值。
Also, you are referring to the result as a Cartesian product between the list and itself, but this is not strictly correct: The Cartesian product would have 16 elements (4x4). Your output is a subset of that, namely only the 2-element combinations (with repetition not allowed) of the values of the list.
这篇关于复制迭代器并生成无序自笛产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!