How to join strings from a Cartesian product of two lists

前端 未结 4 464
野趣味
野趣味 2021-01-28 11:15

I have two lists of strings:

letters = [\'abc\', \'def\', \'ghi\']
numbers = [\'123\', \'456\']

I want to for loop through them to create a lis

4条回答
  •  Happy的楠姐
    2021-01-28 11:33

    Take the product of numbers and letters (rather than letters and numbers), but then join the resulting tuples in reverse order.

    >>> from itertools import product
    >>> [''.join([y, x]) for x, y in product(numbers, letters)]
    ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']
    

    For 2-tuples, y + x would be sufficient rather than using ''.join.

    The product of two lists is just the set of all possible tuples created by taking an element from the first list and an element from the second list, in that order.

    >>> list(product(numbers, letters))
    [('123', 'abc'), ('123', 'def'), ('123', 'ghi'), ('456', 'abc'), ('456', 'def'), ('456', 'ghi')]
    

提交回复
热议问题