简体   繁体   中英

Filter out nested lists by the first element in them

I want to filter nested lists based on the first element in each list. I have the following nested lists:

# 'nom' is duplicated
input1 = [
    ['nom', 'N', 'eye'],
    ['nom', 'N', 'face'],
    ['acc', 'E', 'computer'],
    ['dat', 'C', 'screen']
    ]

# 'acc' is duplicated
input2 = [
    ['nom', 'O', 'heart'],
    ['acc', 'O', 'root'],
    ['acc', 'C', 'life'],
    ['dat', 'E', 'evidence']
    ]

# No duplicates
input3 = [
    ['nom', 'O', 'author'],
    ['acc', 'O', 'tear'],
    ]

For each parent list, I would like to find the child lists whose first element is the same, and keep the first child list in the output. So I want to have the following output:

# From input1
# keep ['nom', 'N', 'eye']
# delete ['nom', 'N', 'face']
output1 = [
    ['nom', 'N', 'eye'],
    ['acc', 'E', 'computer'],
    ['dat', 'C', 'screen']
    ]

# From input2
# keep ['acc', 'O', 'root']
# delete ['acc', 'C', 'life']
output2 = [
    ['nom', 'O', 'heart'],
    ['acc', 'O', 'root'],
    ['dat', 'E', 'evidence']
    ]

# From input3
# keep every child list since there is no duplicate
output3 = [
    ['nom', 'O', 'author'],
    ['acc', 'O', 'tear'],
    ]

How should I achieve this with python3?

If you are using Python 3.6 or newer you can use the fact that dict retain the insertion order. Iterate over the list in reverse and insert it to a dict , and than reverse the values

def filter_list(lst):
    d = {lst[i][0]: lst[i] for i in range(len(lst) - 1, -1, -1)}
    return list(reversed(d.values()))

input1 = filter_list(input1)
print(input1) # [['nom', 'N', 'face'], ['acc', 'E', 'computer'], ['dat', 'C', 'screen']]

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