0

我有两个字符串池,我想对两者进行循环。例如,如果我想把两个贴有标签的苹果放在一个盘子里,我会写:

basket1 = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
    for fruit1 in basket1:

       basket2 = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
       for fruit2 in basket2:

            if fruit1 == fruit2:
                print 'Oops!'

            else:
                print "New Plate = %s and %s" % (fruit1, fruit2)

但是,我不希望顺序很重要——例如,我正在考虑将 apple#1-apple#2 等同于 apple#2-apple#1。编写此代码的最简单方法是什么?

我正在考虑在第二个循环中创建一个计数器来跟踪第二个篮子,而不是每次都从第二个循环中的零点开始。

4

3 回答 3

3

如果您将不等式 ( !=) 更改为小于 ( <),并且您的列表(篮子)已排序且相同,那么一旦您拥有 (a,b),您将不会得到 (b,a)。

所以

fruits = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
[(f1, f2) for f1 in fruits for f2 in fruits if f1 != f2]

变成

fruits = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
[(f1, f2) for f1 in fruits for f2 in fruits if f1 < f2]

但是,如果您有两个不同的列表,

fruits1 = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
fruits2 = ['apple#1', 'apple#2', 'apple#3', 'apple#4', 'orange#1', 'orange#2']

您仍然可以使用上面的技术,稍作修改:

[(f1, f2) for f1 in fruits1 for f2 in fruits2 if f1 < f2]
于 2013-11-01T15:35:33.290 回答
2

最简单的方法是使用itertools.combinations

from itertools import combinations

for tup in combinations(basket1,2):
    print 'New Plate = {} and {}'.format(*tup)

New Plate = apple#1 and apple#2
New Plate = apple#1 and apple#3
New Plate = apple#1 and apple#4
New Plate = apple#2 and apple#3
New Plate = apple#2 and apple#4
New Plate = apple#3 and apple#4
于 2013-11-01T15:35:06.210 回答
0

如果,您有两个不同的列表,或者您无法将一种水果与另一种水果进行比较。

from itertools import product

basket1 = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
basket2 = ['apple#3', 'apple#4', 'apple#5', 'apple#6']

result = []

for tup in product(basket1, basket2):
    if (tup[0] != tup[1]) and (set(tup) not in result):
        result.append(set(tup))
        print "New Plate = %s and %s" % (tup[0], tup[1])

New Plate = apple#1 and apple#3
New Plate = apple#1 and apple#4
New Plate = apple#1 and apple#5
New Plate = apple#1 and apple#6
New Plate = apple#2 and apple#3
New Plate = apple#2 and apple#4
New Plate = apple#2 and apple#5
New Plate = apple#2 and apple#6
New Plate = apple#3 and apple#4
New Plate = apple#3 and apple#5
New Plate = apple#3 and apple#6
New Plate = apple#4 and apple#5
New Plate = apple#4 and apple#6
于 2013-11-01T16:20:49.947 回答