How to join strings from a Cartesian product of two lists

前端 未结 4 419
野趣味
野趣味 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条回答
  •  长情又很酷
    2021-01-28 11:26

    Given your lists of prefixes letters and suffixes numbers that have to be combined

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

    Basic

    The first solution that comes to mind (especially if you are new to Python) is using nested loops

    result = []
    for s in letters:
        for n in numbers:
            result.append(s+n)
    

    and since - as you said - order is irrelevant, also the following will be a valid solution

    result = []
    for n in numbers:
        for s in letters:
            result.append(s+n)
    

    The most important downside of both is that you need to define the result variable before in a way that looks a bit weak.

    Advanced

    If you switch to list comprehension you can eliminate that extra line

    result = [s+n for n in numbers for s in letters]
    

    Expert

    Mathematically spoken, you are creating the Cartesian product of numbers and letters. Python provides a function for exact that purpose by itertools.product (which, by the way, also eliminates the double fors)

    from itertools import product
    result = [''.join(p) for p in product(letters, numbers)]
    

    this may look like overkill in your very example, but as soon as it comes to more components for building results, it may be a big difference, and all tools presented here but itertools.product will tend to explode then.

    For illustration, I conclude with an example that loops over prefixes, infixes, and postfixes:

    print([''.join(p) for p in product('ab', '+-', '12')])
    

    that gives this output:

    ['a+1', 'a+2', 'a-1', 'a-2', 'b+1', 'b+2', 'b-1', 'b-2']
    

提交回复
热议问题