1

这是我的代码,一切正常,除了 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
[]

其他代码工作正常,仅在“高级”代码上如何使列表变为四个单词而不从中删除任何字符串?

4

1 回答 1

1

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

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语句在那里结束函数,然后,当它被放置在循环中时,它不会多次返回。

于 2013-10-28T20:35:46.247 回答