Search code examples
pythontupleslist-comprehensionpython-itertoolscheeseshop

How to pythonicly improve a list comprehension


What follows is a (working) attempt to compose tuples such that the i'th member of the i'th tuple is taken from the second tuple, with the remaining being taken from the first.

just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
shop_window = tuple(tuple(no if i!=j else gone 
                          for i, no in enumerate(just_no)) 
                    for j, gone in enumerate(missing))
print(shop_window, "\nWhat a senseless waste of human life.") 
# (('Caerphilly', 'Danish Blue', 'Cheshire'), ('Gruyere', 'Red Windsor', 'Cheshire'), ('Gruyere', 'Danish Blue', 'Camembert'))
# What a senseless waste of human life.

Much that it works, I'm wondering whether or not there's a more elegant solution, possibly using itertools?


Solution

  • One-liner based on Python indexing/slicing:

    just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
    missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
    shop_window = tuple(just_no[:i] + (gone,) + just_no[i+1:] for i, gone in enumerate(missing))
    print(shop_window)
    

    The output:

    (('Caerphilly', 'Danish Blue', 'Cheshire'), ('Gruyere', 'Red Windsor', 'Cheshire'), ('Gruyere', 'Danish Blue', 'Camembert'))