给定术语的移位列表

2024-04-29 10:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

["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"]

Tags: 列表list术语lettermagicify
3条回答

你在电脑世界里寻找的是一个循环的转变。常用的数据结构是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而不是list,您可以提高所有这些的效率。这样就可以删除函数中的第一个转换步骤。你知道吗

^{}解决:

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']

你能做到的

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

相关问题 更多 >