这是我的代码,除了def advance(stringlist)之外,其他一切都正常

def printList(stringlist):
    print stringlist or []
def add (stringlist, string):
    item = [] if string is None else [string]
    return item + (stringlist or [])
def current (stringlist):
    item =''
    return item + stringlist[0]
def advance(stringlist):
    item = []
    item2 = item + stringlist[1:]
    for item in range(5):
        return item2


我正在寻找结果

>>> myList = None
>>> printList(myList)
[]
>>> for word in ['laundry','homework','cooking','cleaning']:
...     myList = add(myList, word)
...     printList(myList)
...
[laundry]
[homework, laundry]
[cooking, homework, laundry]
[cleaning, cooking, homework, laundry]
>>> current(myList)
'cleaning'
>>> for i in range(5):
...     myList = advance(myList)
...     printList(myList)
...     print current(myList)
...
[cooking, homework, laundry, cleaning]
cooking
[homework, laundry, cleaning, cooking]
homework
[laundry, cleaning, cooking, homework]
laundry
[cleaning, cooking, homework, laundry]
cleaning
[cooking


但我越来越

['cooking', 'homework', 'laundry']
cooking
['homework', 'laundry']
homework
['laundry']
laundry
[]


其他代码只能在“高级”代码上正常工作
我怎样才能使列表变成四个单词而不从中删除任何字符串?

最佳答案

您正在寻找列表轮换;使用某些列表片最容易做到这一点:

def advance(stringlist):
    return stringlist[1:] + stringlist[:1]


这将使用列表的第一个元素,并将其放置在新列表的末尾:

>>> def advance(stringlist):
...     return stringlist[1:] + stringlist[:1]
...
>>> advance(['cooking', 'homework', 'laundry', 'cleaning'])
['homework', 'laundry', 'cleaning', 'cooking']


您的版本仅返回了stringlist[1:](因此,除了第一个元素以外的所有内容); return语句在那里结束该函数,然后,将其置于循环中不会多次返回。

关于python - 列出范围,并重复列出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19644546/

10-12 21:13