简体   繁体   English

在元组列表中查找并移动元组

[英]finding and moving a tuple in a list of tuples

What is the most efficient way of finding a certain tuple based on eg the second element of that tuple in a list and move that tuple to the top of the list Something of the form: 基于例如列表中该元组的第二个元素来查找某个元组并将该元组移动到列表顶部的最有效方法是什么?表格中的某些内容:

LL=[('a','a'),('a','b'),('a','c'),('a','d')]
LL.insert(0,LL.pop(LL.index( ... )))

where I would like something in index() that would give me the position of the tuple that has 'c' as second element. 我希望index()中的某些内容能够让我获得具有'c'作为第二个元素的元组的位置。

Is there a classic python 1-line approach to do that? 有没有经典的python 1行方法呢?

To find position you can: 要找到位置,您可以:

positions = [i for i, tup in enumerate(LL) if tup[1] == 'c']

You can now take the index of the desired element, pop it and push to the beginning of the list 您现在可以获取所需元素的索引,弹出它并按到列表的开头

pos = positions[0]
LL.insert(0, LL.pop(pos))

But you can also sort your list using the item in the tuple as key: 但您也可以使用元组中的项目作为键对列表进行排序:

sorted(LL, key=lambda tup: tup[1] == 'c', reverse=True)

if you don't care about order of the other elements 如果你不关心其他元素的顺序

>>> LL.insert(0,LL.pop([x for x, y in enumerate(LL) if y[1] == 'c'][0]))
>>> LL
[('a', 'c'), ('a', 'a'), ('a', 'b'), ('a', 'd')]
>>> 

2 lines, however 1 line solutions are all inefficient 2行,但是1行解决方案都是低效的

>>> LL=[('a','a'),('a','b'),('a','c'),('a','d')]
>>> i = next((i for i, (x, y) in enumerate(LL) if y == 'c'), 0) # 0 default index
>>> LL[0], LL[i] = LL[i], LL[0]
>>> LL
[('a', 'c'), ('a', 'b'), ('a', 'a'), ('a', 'd')]

This does nothing if the index is not found 如果找不到索引,则不执行任何操作

>>> LL=[('a','a'),('a','b'),('a','c'),('a','d')]
>>> i = next((i for i, (x, y) in enumerate(LL) if y == 'e'), 0) # 0 default index
>>> LL[0], LL[i] = LL[i], LL[0]
>>> LL
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd')]

The problem with terse, pythonic, 'fancy schmancy' solutions is the code might not be easily maintained and/or reused in other closely aligned contexts. 简洁,pythonic,'花式schmancy'解决方案的问题是代码可能不容易在其他紧密对齐的上下文中维护和/或重用。

It seems best to just use 'boiler plate' code to do the search, and then continue with the application specific requirements. 最好只使用“锅炉板”代码进行搜索,然后继续应用程序的特定要求。

So here is an example of easy to understand search code that can be easily 'plugged into' when these questions come up, including those situations when we need to know if the key is found. 所以这里有一个易于理解的搜索代码的例子,当这些问题出现时,可以很容易地“插入”,包括那些我们需要知道是否找到密钥的情况。

def searchTupleList(list_of_tuples, coord_value, coord_index):
    for i in range(0, len(list_of_tuples)):
        if list_of_tuples[i][coord_index] == coord_value:
            return i               # matching index in list
    return -1                      # not found

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

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