在 python 中搜索嵌套列表
我有一个包含 97510 个值的元组的嵌套列表,如下所示:
a = [ (1,2,3), (3,4,5), (5,4,2)]
每个第一个值(索引 = 0)都是唯一的,我需要找到具有相同索引 = 1 项的其他索引 = 0 项 在示例中,我需要找到第二个和第三个元组,其中第二项“4”是常见的。
我该怎么做?
I have a nested list of tuples of 97510 values like this:
a = [ (1,2,3), (3,4,5), (5,4,2)]
every first value (index=0) is unique and I need to find other index=0 items that have the same index=1 items
In the example , I need to find the second and third tuples where the the second item '4' is common .
How do I do it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想查找所有匹配项:
如果您想挑选特定第二个值的所有匹配项:
编辑:如注释,列表理解是更好的选择,因为它对于此类工作更有效:
使用
timeit
显示列表理解速度大约快 2.5 倍(无论如何在我的机器上):If you want to find all matches:
If you want to pick out all matches for a particular second value:
Edit: As pointed out in the comments, a list comprehension is preferable as it is more efficient for such work:
Using
timeit
shows the list comprehension is about 2.5 times faster (on my machine anyway):这是一种方法:
这将生成一个列表字典,其中具有相同第二个值的所有项目都在一个列表中,并以该值作为键。
Here is one way to do it:
This will result in a dictionary of lists where all items with the same second value are in one list, with that value as the key.
另一种选择:
Another alternative:
请注意,您还可以使用 groupby:
根据评论
进行 编辑问题并找到了另一种解决方案 - 但不是最好的解决方案,但是:
Note that you can also use groupby:
Edited as per comment
Played around with the problem and found one more solution - however not the best one, but: