简体   繁体   English

在嵌套列表中查找匹配项

[英]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. 我的输出列表按照我的stlist的升序生成名称。 ie Tom, Joh, Sam, Tommy, Nanni, Ron but I want the outputlist to be in the same order as the stlist. 即Tom,Joh,Sam,Tommy,Nanni,Ron但我希望outputlist与stlist的顺序相同。

My Python code is: 我的Python代码是:

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 从上面的代码显示的输出列表是:Tom,Joh,Sam,Tommy,Nanni,Ron而不是

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. 所以它实际上按升序排序我的1stlist并按顺序打印第二个列表中的名称。但是如果我的stlist按升序排列,则输出列表就可以了。

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循环:

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'] 此外,if语句应该是这样的: if element == sublist[1]:或者元素'1'可以在某个ndlist元素中找到,如下所示: ['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. 为了提高效率,您可以尝试对ndlist进行排序和执行二进制搜索以检查元素是否存在。

You could use sorted and a custom sort key (a Lambda function) to do this: 您可以使用sorted和自定义排序键(Lambda函数)来执行此操作:

>>> [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. 这行代码使用ndlist中数字的位置作为排序键对stlist进行排序,然后列表stlist构建一个仅包含名称的新列表。

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: 除了嵌套循环或排序之外,您还可以使用一个线性运行ndlist创建映射,然后使用另一个线性运行stlist来构建结果列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM