[英]Using a while loop to return a function
在主函数中:
创建一个包含最近美国总统姓氏的列表,以肯尼迪开头,以奥巴马结尾,按时间顺序排列。 使用 for 循环遍历整个列表,在自己的行上打印每个总统的名字。 通过从列表中删除前两位总统和最后两位总统来切片。 将新切片作为参数传递给名为 playlist 的自定义函数。 使用 while 循环显示播放列表返回的列表中的元素。
在播放列表功能中:
打印切片列表的大小。 使用列表功能。 按逆字母顺序对切片列表进行排序。 将此列表返回到主列表。
这是我到目前为止。 我不知道如何插入 while 循环。 每次我这样做时,列表都会继续运行或不显示。
def main():
#Create list.
names = ['Kennedy', 'Johnson', 'Nixon', 'Ford', 'Carter', 'Reagan', 'Bush', 'Clinton', 'Bush', 'Obama']
sliced_list = names[2:8]
#Display the list.
print('Here are the most recent presidents of the USA')
for n in names:
print(n)
sliced = playlist(sliced_list)
def playlist(sliced_list):
size = len(sliced_list)
print('The list size is now', size)
sliced_list.sort()
sliced_list.reverse()
return sliced_list
main()
这是它应该回来的方式。
Original list in main:
Kennedy
Johnson
Nixon
Ford
Carter
Reagan
Bush
Clinton
Bush
Obama
Not in main: list size is now 6
Back in main, list in reverse alpha order
Reagan
Nixon
Ford
Clinton
Carter
Bush
要使用while
循环遍历列表元素而不修改列表:
i = 0
while i < len(sliced):
print(sliced[i])
i += 1
如果您更喜欢 browskie 建议的改变列表的方法,我建议避免使用 try-except 块,如下所示:
while len(sliced):
print(sliced.pop(0))
Python while 循环是一个简单的循环,只要满足其条件就会循环,因此如果您执行类似while i<5:
,它将循环直到i
等于或大于 5。
此外,在python中,您可以使用len(lst)
来获取列表的长度,也可以执行lst[i]
(其中 i 是一个称为索引的整数)来获取该位置的元素,例如在原始列表中,如果我们执行names[1]
,它将返回Johnson
。
现在在您的 while 循环中,您希望从 0 开始循环到列表的长度,并在每个索引处打印列表元素。 我希望您可以根据所有信息创建您需要的程序。
你可以尝试这样的事情:
sliced = playlist(sliced_list) #This is from your code
while True: #Will run forever
try:
#And try to remove and print out the first item from the list
print(sliced.pop(0))
except:
#As soon as it exhausts the list and fails, it will stop the loop
break
我想你快到了。 while 循环将继续直到切片列表为空。
def main():
#Create list.
names = ['Kennedy', 'Johnson', 'Nixon', 'Ford', 'Carter', 'Reagan', 'Bush', 'Clinton', 'Bush', 'Obama']
for name in names: #for to print names
print name
sliced = playlist(names[2:-2]) # slice
while len(sliced): # while there is names in sliced do:
print sliced.pop() # removes the last name on sliced and prints it
def playlist(sliced_list):
size = len(sliced_list)
print('The list size is now', size)
sliced_list.sort()
sliced_list.reverse()
return sliced_list
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.