Python: Merge list with range list

后端 未结 2 1498
青春惊慌失措
青春惊慌失措 2021-02-19 22:12

I have a list:

L = [\'a\', \'b\']

I need to create a new list by concatenating an original list which ra

相关标签:
2条回答
  • 2021-02-19 22:45

    My solution almost same, but the output is in different order...

    does order matter?

    Here is my solution

    from itertools import product
    L = ['a', 'b']
    k = 4
    L2 = range(1, k+1)
    print [x+ str(y) for x,y in list(product(L,L2))]
    

    output:

    ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4']
    
    0 讨论(0)
  • 2021-02-19 23:01

    You can use a list comprehension:

    L = ['a', 'b']
    k = 4
    L1 = ['{}{}'.format(x, y) for y in range(1, k+1) for x in L]
    print(L1)
    

    Output

    ['a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4']
    
    0 讨论(0)
提交回复
热议问题