2013-11-01 3 views
0

У меня есть два пула строк, и я хотел бы сделать цикл над обоими. Например, если я хочу поставить два маркированных яблоки в одной тарелке Напишу:Строковые контуры в Python

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) 

Однако, я не хочу, чтобы значения - например, я рассматриваю яблоко # 1-яблоко # 2 эквивалентно яблоку # 2-яблоку # 1. Какой самый простой способ кодировать это?

Я думаю о создании счетчика во втором цикле, чтобы отслеживать вторую корзину, а не начинать с нулевой точки во втором цикле каждый раз.

+1

Я не вижу 'оранжевых' 'в вашем вышеуказанном коде. – roippi

+0

Извините, я отредактировал его! – Rotail

ответ

3

При изменении неравенства (!=) менее (<), и ваши списки (корзины) сортируются и то же, вы не получите (b, a), если у вас есть (a, b).

Так

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] 
+0

Хорошее решение - вы могли бы обобщить, если на самом деле есть два разных списка. – wrhall

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 
+0

Не нужно материализовывать комбинации с помощью 'list()'. – DSM

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 
Смежные вопросы