+ 1
How to combine lists as given in the example?
Example: list_1 = ["apple", "banana", "orange"] list_2 = ["spam", "eggs", "beef"] is it possible for the output to end up like this: ["apple", "spam", "banana", "eggs", "orange", "beef"] or maybe even randomize its position?
5 odpowiedzi
+ 4
Numpy is useful here:
import numpy as np
print(np.array([i for i in list(zip(list_1, list_2))]).ravel())
If you want without numpy use this:
f̶̶̶o̶̶̶r̶̶̶ ̶̶̶i̶̶̶,̶̶̶ ̶̶̶v̶̶̶ ̶̶̶i̶̶̶n̶̶̶ ̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶(̶̶̶z̶̶̶i̶̶̶p̶̶̶(̶̶̶r̶̶̶a̶̶̶n̶̶̶g̶̶̶e̶̶̶(̶̶̶1̶̶̶,̶̶̶ ̶̶̶6̶̶̶,̶̶̶ ̶̶̶2̶̶̶)̶̶̶,̶̶̶ ̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶2̶̶̶)̶̶̶)̶̶̶:̶ ̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶1̶̶̶.̶̶̶i̶̶̶n̶̶̶s̶̶̶e̶̶̶r̶̶̶t̶̶̶(̶̶̶i̶̶̶n̶̶̶t̶̶̶(̶̶̶i̶̶̶)̶̶̶,̶̶̶ ̶̶̶v̶̶̶)̶̶̶ ̶̶̶p̶̶̶r̶̶̶i̶̶̶n̶̶̶t̶̶̶(̶̶̶l̶̶̶i̶̶̶s̶̶̶t̶̶̶_̶̶̶1̶̶̶)̶̶̶
I suggest you to go for Ipang 's method
+ 4
list_1 = ["apple", "banana", "orange"]
list_2 = ["spam", "eggs", "beef"]
# extend() works
list_combined = []
for x, y in zip(list_1, list_2):
list_combined.extend((x, y))
print(list_combined)
# append() also works
list_combined = []
for x, y in zip(list_1, list_2):
list_combined.append(x)
list_combined.append(y)
print(list_combined)
You can also shuffle <list_1> and <list_2> before extending or appending to <list_combined>.
+ 1
list_1 = ["apple", "banana", "orange"]
list_2 = ["spam", "eggs", "beef"]
tl = list()
for x in zip(list_1, list_2 ):
tl.extend(x)
print(tl)
0
Easily adding both list as👇👇
list3=list1+list2
print(list3)
0
List1.extend(list2)
With the method extend you don't need to loop in the list. Extend deconstfucts an iterable and adds its elements to the list.