How to merge lists into a list of tuples?

后端 未结 8 2017
你的背包
你的背包 2020-11-21 22:30

What is the Pythonic approach to achieve the following?

# Original lists:

list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]

# List of tuples from \'list_a\' and          


        
8条回答
  •  独厮守ぢ
    2020-11-21 23:09

    I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.

    >>> list_1 = ['Ace', 'King']
    >>> list_2 = ['Spades', 'Clubs', 'Diamonds']
    >>> deck = []
    >>> for i in range(max((len(list_1),len(list_2)))):
            while True:
                try:
                    card = (list_1[i],list_2[i])
                except IndexError:
                    if len(list_1)>len(list_2):
                        list_2.append('')
                        card = (list_1[i],list_2[i])
                    elif len(list_1)>>
    >>> #and the result should be:
    >>> print deck
    >>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
    

提交回复
热议问题