从给定的术语转移列表

时间:2015-10-13 20:05:19

标签: python list python-2.7

基本上,我在这里有一个清单:

["a", "b", "c", "d", "e"]

鉴于列表中的特定术语(即"c"),如何使列表循环一次,最后一次返回到开头?

这就是我的意思:

>>> list = ["a", "b", "c", "d", "e"]
>>> letter = "c"
>>> list = magicify(list, letter)
>>> list
["c", "d", "e", "a", "b"]
>>> letter = "a"
>>> magicify(list, letter)
["a", "b", "c", "d", "e"]

3 个答案:

答案 0 :(得分:2)

你可以做到

def magicify(list, letter):
    return list[list.index(letter):]+list[:list.index(letter)]

答案 1 :(得分:0)

itertools.cycle的解决方案:

from itertools import cycle

lst = ["a", "b", "c", "d", "e"]
pool = cycle(lst)

new = []
start = False
for item in pool:
    if item == 'c':
        start = not start
        if not start:
            break
    if start:
        new.append(item)

print new

>>> ['c', 'd', 'e', 'a', 'b']

答案 2 :(得分:0)

您在计算机世界中寻找的是循环移位。用于此的常见数据结构是deque

假设您的元素是唯一的,或者您还有其他方法可以找出“起始元素”的索引。

from collections import deque

def magicify(mylist, letter):
    mydeque = deque(mylist)

    # Keep shifting elements on the right to the left until
    # you hit the chosen value (letter)
    popped = mydeque.pop()
    while (popped != letter):
        mydeque.appendleft(popped)
        popped = mydeque.pop()
    mydeque.appendleft(letter)

    return mydeque

通过使用deque整个时间而不是列表,您可以提高所有这些效率。这样您就可以删除函数中的第一个转换步骤。