Rotail
Rotail

Reputation: 1061

String loops in Python

I have two pools of strings and I would like to do a loop over both. For example, if I want to put two labeled apples in one plate I'll write:

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)

However, I don't want order to matter -- for example I am considering apple#1-apple#2 equivalent to apple#2-apple#1. What's the easiest way to code this?

I'm thinking about making a counter in the second loop to track the second basket and not starting from the point-zero in the second loop every time.

Upvotes: 1

Views: 104

Answers (3)

Will Hunter
Will Hunter

Reputation: 1

If, you have two distinct lists or you cannot compare with one fruit to another.

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

Upvotes: 0

Squidly
Squidly

Reputation: 2717

If you change inequality (!=) to less than (<), and your lists (baskets) are sorted and the same, you won't get (b,a) once you have (a,b).

So

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

becomes

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

If, however, you have two distinct lists,

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

You could still use the technique from above with a slight modification:

[(f1, f2) for f1 in fruits1 for f2 in fruits2 if f1 < f2]

Upvotes: 3

roippi
roippi

Reputation: 25954

Easiest way is to just use 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

Upvotes: 2

Related Questions