假设我有这样的东西:
L1=['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse'...]
for x in L1:
input1= open('file_%s'%(x), 'r')
file1= pickle.load(input1)
for x in L1:
input2= open('file_%s'%(x), 'r')
file2= pickle.load(input2)
我想得到文件的每一个组合,而不是重复已经做过的组合(一旦cat_dog完成,就不要再做dog_cat )。有没有办法让我这么做?我真正的列表是按字母顺序排列的,如果这有什么不同的话。
发布于 2011-02-24 15:20:04
您也可以将其作为生成器来执行:
L1=['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse']
tuples = [(x,y) for x in L1 for y in L1 if x != y]
for entry in tuples:
if (entry[1], entry[0]) in tuples:
tuples.remove((entry[1],entry[0]))
for pair in tuples:
input1= open('file_%s'%(pair[0]), 'r')
file1= pickle.load(input1)
input2= open('file_%s'%(pair[1]), 'r')
file2= pickle.load(input2)
在第一个循环之后,tuples
的内容是:
('cat', 'dog')
('cat', 'fish')
('cat', 'rabbit')
('cat', 'horse')
('cat', 'bird')
('cat', 'frog')
('cat', 'mouse')
('dog', 'fish')
('dog', 'rabbit')
('dog', 'horse')
('dog', 'bird')
('dog', 'frog')
('dog', 'mouse')
('fish', 'rabbit')
('fish', 'horse')
('fish', 'bird')
('fish', 'frog')
('fish', 'mouse')
('rabbit', 'horse')
('rabbit', 'bird')
('rabbit', 'frog')
('rabbit', 'mouse')
('horse', 'bird')
('horse', 'frog')
('horse', 'mouse')
('bird', 'frog')
('bird', 'mouse')
('frog', 'mouse')
发布于 2011-02-24 14:59:59
实际上,您要问的是如何生成名称列表中包含的两个项的所有组合(而不是,这是它们的可能组合)。
这意味着您可以使用内置的itertools.combinations()
生成器函数轻松(高效地)生成所需的名称对,而无需重复:
L1 = ['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse']
for pair in combinations(L1, 2):
print(pair)
input1 = open('file_%s' % pair[0], 'r')
input2 = open('file_%s' % pair[1], 'r')
已处理的对:
('cat', 'dog')
('cat', 'fish')
('cat', 'rabbit')
('cat', 'horse')
('cat', 'bird')
('cat', 'frog')
('cat', 'mouse')
('dog', 'fish')
('dog', 'rabbit')
('dog', 'horse')
('dog', 'bird')
('dog', 'frog')
('dog', 'mouse')
('fish', 'rabbit')
('fish', 'horse')
('fish', 'bird')
('fish', 'frog')
('fish', 'mouse')
('rabbit', 'horse')
('rabbit', 'bird')
('rabbit', 'frog')
('rabbit', 'mouse')
('horse', 'bird')
('horse', 'frog')
('horse', 'mouse')
('bird', 'frog')
('bird', 'mouse')
('frog', 'mouse')
发布于 2011-02-24 14:58:40
使用示例:
>>> list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4),
(3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
第一个参数是可迭代的,第二个是r
,返回子序列的长度。
然后,您可以使用map或理解轻松地连接结果:
map(lambda x: x[0] + "_" + x[1], itertools.combinations(["cat", "dog", "fish"], 2)))
lambda中的x
是一个r
-sized元组。
上面的结果将是:
['cat_dog', 'cat_fish', 'dog_fish']
https://stackoverflow.com/questions/5106228
复制相似问题