How do i add two lists' elements into one list?

前端 未结 4 1086
执笔经年
执笔经年 2020-12-10 12:13

For example, I have a list like this:

list1 = [good, bad, tall, big]

list2 = [boy, girl, guy, man]

and I want to make a list like this:

相关标签:
4条回答
  • 2020-12-10 12:29

    Using zip

    list3 = []
    for l1,l2 in zip(list1,list2):
        list3.append(l1+l2)
    

    list3 = ['goodboy', 'badgirl', 'tallguy', 'bigman']

    0 讨论(0)
  • 2020-12-10 12:31

    for this or any two list of same size you may also use like this:

    for i in range(len(list1)):
        list3[i]=list1[i]+list2[i]
    
    0 讨论(0)
  • 2020-12-10 12:33

    You can use list comprehensions with zip:

    list3 = [a + b for a, b in zip(list1, list2)]
    

    zip produces a list of tuples by combining elements from iterables you give it. So in your case, it will return pairs of elements from list1 and list2, up to whichever is exhausted first.

    0 讨论(0)
  • 2020-12-10 12:38

    A solution using a loop that you try is one way, this is more beginner friendly than Xions solution.

    list3 = []
    for index, item in enumerate(list1):
        list3.append(list1[index] + list2[index])
    

    This will also work for a shorter solution. Using map() and lambda, I prefer this over zip, but thats up to everyone

    list3 = map(lambda x, y: str(x) + str(y), list1, list2);
    
    0 讨论(0)
提交回复
热议问题