I have two lists of strings and I want to concatenate them index wise in commutative way(AB = BA). I was able to get the output but I need some optimal way to do it. Two lists are:
bus0 = ['NEVP', 'IPCO']
bus1 = ['CISO', 'DUK']
Expected output:
all links: ['NEVP-CISO', 'IPCO-DUK', 'CISO-NEVP', 'DUK-IPCO']
The way I did it some thing like this
link1 = ['-'.join([i, j ]) for i, j in zip(bus0, bus1)]
link2 = ['-'.join([j, i]) for i, j in zip(bus0, bus1)]
allPossibleLinks = link1 link2
print('link1: ', link1)
print('link2: ', link2)
print('all links: ', allPossibleLinks)
As you can see I use two for loops, so I want to is there a method to do this in one loop or any other better way?
CodePudding user response:
You can do it all in one loop, just not a list comprehension (technically you can, it would just get ugly).
bus0 = ['NEVP', 'IPCO']
bus1 = ['CISO', 'DUK']
all_links = []
for i, j in zip(bus0, bus1):
all_links.append(f'{i}-{j}')
all_links.append(f'{j}-{i}')
CodePudding user response:
the answer is asked in this order
['NEVP-CISO', 'IPCO-DUK', 'CISO-NEVP', 'DUK-IPCO']
not
['NEVP-CISO', 'CISO-NEVP', 'IPCO-DUK', 'DUK-IPCO']
all_links = []
temp = []
for (i,j) in zip(bus0, bus1):
all_links.append(i '-' j)
temp.append(j '-' i)
all_links.extend(temp)
print(all_links)
Output now looks like -
['NEVP-CISO', 'IPCO-DUK', 'CISO-NEVP', 'DUK-IPCO']