简体   繁体   中英

Python zip() without parantheses

I am trying to combine two list based on user input using the zip() function. But I want the result to not have the extra brackets.

lst1 = []

# For list of strings/chars
lst2 = []

lst1 = [int(item) for item in input("Enter the list items : ").split()]

lst2 = [int(item) for item in input("Enter the list items : ").split()]

print(lst1)
print(lst2)

print([list(a) for a in zip(lst1,lst2)])
Output = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
Desired output = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

See this answer .

print([e for t in zip(lst1, lst2) for e in t])
from itertools import chain

lst1 = []

# For list of strings/chars
lst2 = []

lst1 = [int(item) for item in input("Enter the list items : ").split()]

lst2 = [int(item) for item in input("Enter the list items : ").split()]

# fist method
print(list(chain.from_iterable([a for a in zip(lst1,lst2)])))

# second method
total_list = []
for a, b in zip(lst1,lst2):
    total_list.append(a)
    total_list.append(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM