I want to merge 2 lists in one list, and in this one list I can find the elements of the two lists at the same order for example: input:
['10','22','3','4','5']
['22','3','5']
the output should be:
['10','22','3','4','5']
The goal is to combine multiple sequences of tasks to do in one sequence in which we can pass all the tasks. I used the code below but it repeats many tasks that we can eliminate logically, I want to optimize it more.
def merge(L,R):
S=[]
n=min(len(L),len(R))
for i in range(n):
if L[i]==R[i]:
S.append(L[i])
else:
S.append(L[i])
S.append(R[i])
if len(L)>len(R):
return(S+list(k for k in L[n:]))
if len(R)>len(L):
return(S+list(k for k in R[n:]))
if len(L)==len(R):
return(S)
# n is the number of tasks written in a text file before tasks and each task is written on a line
n=int(input())
resultat=[]
for i in range(n):
line=input().split()
resultat=merge(resultat,line)
print(resultat)
Your question is unclear.
In case you want to merge the lists of tasks and execute each task once only, we can use sets:
l1=['A' ,'B' ,'C' ,'D' ,'F']
l2=['C', 'D', 'E', 'F']
l3=['A', 'B', 'C', 'F']
l4=['A', 'C', 'B', 'F']
l5=['A','C' ,'D' ,'E' ,'F']
l6=['B', 'C', 'D', 'E', 'F']
import itertools as it
s = set(it.chain(l1, l1, l3, l4, l5, l6)))
print(list(s))
produces
['A', 'B', 'F', 'E', 'D', 'C']
Else, if you want a unique set of tasks at each step of every list in parallel
lo = [e for t in it.zip_longest(l1, l2, l3, l4, l5, l6) for e in set(t) if e is not None]
print(lo)
produces
['B', 'A', 'C', 'B', 'D', 'C', 'B', 'E', 'D', 'C', 'F', 'E', 'D', 'F']
In case the input lists vary in number, create a list of lists and check out itertools.chain.from_iterable
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.