简体   繁体   中英

Find matching items in nested list

I'm trying to match a list of items to another list of items of a different dimension and print an element from the second list if the item is matched. For example:

stlist=['6', '3', '4', '2', '5', '1']
ndlist=[['Tom', '1'], ['Joh', '2'], ['Sam', '3'], ['Tommy','4'], ['Nanni', '5'], ['Ron', '6']]

My outputlist is producing the names in the ascending order of my stlist. ie Tom, Joh, Sam, Tommy, Nanni, Ron but I want the outputlist to be in the same order as the stlist.

My Python code is:

for sublist in ndlist:
    for element in stlist:
        if element in sublist[1]:
            print(sublist[0])

The outputlist displayed from the above codes is: Tom, Joh, Sam, Tommy, Nanni, Ron instead of

outputlist = [Ron, Sam, Tommy, Joh, Nanni, Tom]

So it's actually sorting in ascending order my 1stlist and printing the names from the 2ndlist in that order.But if my stlist was in ascending order the outputlist would be fine.

Can anyone tell me why please and how should I modify the codes to get my desired outputlist.

Try to rearrange your for loops:

for element in stlist:
    for sublist in ndlist:
        if element in sublist[1]:
            print (sublist[0])

Also, the if statement should maybe be like this: if element == sublist[1]: or else the element '1' would be found in some ndlist element like this one: ['foo', '10']

Furthermore, this solution is not the most efficient with large lists. To make it more efficient you could try something like sorting the ndlist and performing binary search to check if an element exists.

You could use sorted and a custom sort key (a Lambda function) to do this:

>>> [i[0] for i in sorted(ndlist, key = lambda x:stlist.index(x[1]))]
['Ron', 'Sam', 'Tommy', 'Joh', 'Nanni', 'Tom']

This line of code sorts ndlist using the position of the numbers in stlist as the sort key, then a list comprehension builds a new list containing only the names.

Instead of nesting loops or sorting you could also create a mapping with one linear run through ndlist and then use another linear run through stlist to build the result list:

mapping = dict((b, a) for a, b in ndlist)
result = [mapping[x] for x in stlist]
print(result)

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