Home > Blockchain >  Removing duplicity of items in list of lists based on a specific index #Python
Removing duplicity of items in list of lists based on a specific index #Python

Time:03-01

I have the following lists:

lista = [1,2,3,5]
listb = [1,5,2,6]
listc = [3,5,1,6]
mainList = [lista,listb,listc]

I'd like to remove listb from mainList since it contains the same element as lista at index position[0].

Kinda like the code below, however, applied to every list contained in mainList. basically, remove all lists with index 0 duplicity while maintaining the first one.

if lista[0] == listb[0]:
    mainList.remove(listb)

#But to include duplicity in for all elements in mainList.

Anybody? Thanks in advance!

CodePudding user response:

This does the trick:

lista = [1,2,3,5]
listb = [1,5,2,6]
listc = [3,5,1,6]
listd = [1,7,9,4]
liste = [3,7,4,8]
mainList = [lista,listb,listc,listd,liste]
for o,i in enumerate([n for n,k in enumerate(mainList) if any([k[0]==j[0] for j in mainList[:n]])]):
     del mainList[i-o]
print(mainList) # [[1, 2, 3, 5], [3, 5, 1, 6]]

alternatively you can create a new list with the one line list comprehension:

newList = [k for n,k in enumerate(mainList) if not any([k[0]==j[0] for j in mainList[:n]])]

The fast solution is this:

firsts = set()
result = []
for k in mainList:
    if not firsts.__contains__(k[0]):
        result.append(k)
        firsts.add(k[0])
print(result)

or in place like this:

firsts = set()
i=0
while i<len(mainList):
    if not mainList[i][0] in firsts:
        firsts.add(mainList[i][0])
        i =1
    else:
        del mainList[i]
print(mainList)

CodePudding user response:

You can use the code below-

lista = [1,2,3,5]
listb = [1,5,2,6]
listc = [3,5,1,6]
mainList = [lista,listb,listc]
ml_final = mainList.copy()    #make a copy of the main list, this would be the final list

first_ele = []     #make empty list where first elements of all the lists are added
for i in range(len(mainList)):
  temp = mainList[i][0]
  if temp in first_ele:
    ml_final.pop(i)
  else:
    first_ele.append(temp)

#output
print(ml_list)
#[[1, 2, 3, 5], [3, 5, 1, 6]]
  • Related