简体   繁体   中英

Pop out the whole dic if element of 1st dic in list is repeated?

Here I have a list of dic, where I want to remove duplicates which is equal to 1st element of dic. Input :

data  = [

    [
          [{'color': '1'},{'color': '0'},{'color': '2'},{'color': '1'}],
          [{'color': '2'},{'color': '3'},{'color': '2'},{'color': '5'}],
          [{'color': '1'},{'color': '1'},{'color': '3'},{'color': '3'}]
    ],

    [
          [{'color': '1'},{'color': '1'},{'color': '4'},{'color': '4'}],
          [{'color': '4'},{'color': '3'},{'color': '1'},{'color': '4'}],
          [{'color': '7'},{'color': '1'},{'color': '7'},{'color': '1'}]
    ]

        ]

I have tried and got the expected output, Is there any pythonic way to achieve the same ?

Code :

new = [] ; 
for i in data:
    master = []
    for j in i:
        temp = []
        for k in j:
            if j[0]['color'] != k['color']:
                temp.append(k)
        temp.insert(0,j[0])
        master.append(temp)
    new.append(master)
print(new)

Expected Output :

data  = [

    [
          [{'color': '1'},{'color': '0'},{'color': '2'}],
          [{'color': '2'},{'color': '3'},{'color': '5'}],
          [{'color': '1'},{'color': '3'},{'color': '3'}]
    ],

    [
          [{'color': '1'},{'color': '4'},{'color': '4'}],
          [{'color': '4'},{'color': '3'},{'color': '5'}],
          [{'color': '7'},{'color': '1'},{'color': '1'}]
    ]     
    ]

No need for all the temporary lists:

for item in data:
    for i,subitem in enumerate(item):
        item[i] = [item[i][0]] + [dct for dct in item[i][1:]
                                  if dct['color'] != item[i][0]['color']]

Basically it just iterates through each of the subitems and replaces it with its first item plus the rest of the items that don't have the same value.

Although it's ugly, you can even reduce it to a one-liner (for illustrative purposes only... I wouldn't recommend it because readability):

data = [[[item[i][0]] + [dct for dct in item[i][1:] if dct['color'] != item[i][0]['color']] for i,subitem in enumerate(item)] for item in data]

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