gpt4 book ai didi

python - 在范围内列出并重复列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:22 25 4
gpt4 key购买 nike

这是我的代码,除了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com