How to join strings from a Cartesian product of two lists

前端 未结 4 497
野趣味
野趣味 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:38

    You can try list comprehension with two nested for loop over numbers and then letters :

    print([l+n for n in numbers for l in letters])
    # ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']
    

    You can also use nested for loop:

    out = []
    for n in numbers:
        for l in letters:
            out.append(l+n)
    print(out)
    # ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']
    

    For more details on list comprehension, see either the doc or this related topic.

提交回复
热议问题