这是我的代码,一切正常,除了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
[]
其他代码工作正常,只是在' advance'码 如何使列表成为四个单词而不从中删除任何字符串?
答案 0 :(得分:1)
您正在寻找列表 rotation ;这是最容易完成的一些列表切片:
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
语句在那里结束函数,然后,当它被置于循环中时,它不会多次返回。