简体   繁体   中英

How to concatenate elements of a list into a new list while not repeating the common elements?

I have a 2d list of 2 elements in each row and I want to concatenate two rows with a common element and append it to another list but do not want the common element to be repeated. Here is something similar to what I tried

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']
list2 = []
for i in range(len(list1)-1):
    for j in range(i+1,len(list1)):
      if list1[i][0] in list1[j]:
        if list1[i][1] + list1[j] not in list2:
          list2.append(list1[i][1] + list1[j])
      elif list1[i][1] in list1[j]:
        if list1[i][0] + list1[j] not in list2:
          list2.append(list1[i][0] + list1[j])
print(list2)

but this gives me an error saying "can only concatenate str (not "list") to str" and if I just use "+" to concatenate both lists then common element is added twice. Expected result is

[['apple','orange','banana'],['apple','orange','mango'],['apple','banana','mango'],['banana','mango','orange']]

Surely there must be an easier way to concatenate while excluding common elements.

If I understood you correctly:

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']]
list2 = []

for pair in list1:
   list2.extend(pair)

# Using list(set()) removes duplicates
list2 = list(set(list2))

print(list2)

Another way of unpacking list1:

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']]
list2 = []

def flatten(l):
    return [item for sublist in l for item in sublist]

# Using list(set()) removes duplicates
list2 = list(set(flatten(list1)+list2))

print(list2)

Comment below if it does not answer your question


Useful links:

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