简体   繁体   English

在列表中查找与元组中的第一项相匹配的第一项

[英]finding first item in a list whose first item in a tuple is matched

I have a list of several thousand unordered tuples that are of the format 我有几千个格式如下的无序元组列表

(mainValue, (value, value, value, value))

Given a main value (which may or may not be present), is there a ' nice ' way, other than iterating through every item looking and incrementing a value, where I can produce a list of indexes of tuples that match like this: 给定一个主值(可能存在或可能不存在),是否有一种“ 不错的 ”方法,除了遍历每一项寻找并增加一个值的方法外,我可以生成一个如下所示的元组索引列表:

index = 0;
for destEntry in destList:
if destEntry[0] == sourceMatch:
    destMatches.append(index)
index = index + 1

So I can compare the sub values against another set, and remove the best match from the list if necessary. 因此,我可以将子值与另一组值进行比较,并在必要时从列表中删除最佳匹配项。 This works fine, but just seems like python would have a better way! 这可以正常工作,但似乎python会有更好的方法!

Edit: As per the question, when writing the original question, I realised that I could use a dictionary instead of the first value (in fact this list is within another dictionary), but after removing the question, I still wanted to know how to do it as a tuple. 编辑:根据问题,在编写原始问题时,我意识到我可以使用字典而不是第一个值(实际上此列表在另一个字典中),但是删除问题后,我仍然想知道如何做一个元组。

With list comprehension your for loop can be reduced to this expression: 使用列表理解,您的for循环可以简化为以下表达式:

destMatches = [i for i,destEntry in enumerate(destList) if destEntry[0] == sourceMatch]

You can also use filter() 1 built in function to filter your data: 您还可以使用内置函数filter() 1来过滤数据:

destMatches = filter(lambda destEntry:destEntry[0] == sourceMatch, destList)

1 : In Python 3 filter is a class and returns a filter object . 1 :在Python 3中filter是一个类,它返回一个filter object

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

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