如何使用while循环在一行用制表符分隔的行上显示切片中的所有元素

2024-06-02 07:56:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的家庭作业:

编写一个创造性的程序,演示您对Python列表的理解:
先做一个空列表。
使用循环向列表中添加12个介于50和80之间的随机整数。
按从高到低的降序排列列表。
使用循环将排序后的列表元素打印在一行上,用单个空格隔开。
确定66是否在列表中,并生成一些适当的输出。参见示例输出。
打印列表中最大的元素和列表中最小的元素。
将索引为4到8的五个元素切片,并分配给一个变量。
打印切片。
打印此切片中所有五个元素的总和。
使用while循环将切片中的所有元素显示在一行上,用制表符分隔。在

样本输出

71 70 67 66 62 55 53 52 52 52 51 50 
Yes, 66 is in the list at index 3
71 is the largest element
The smallest element is 50
Here is the slice [62, 55, 53, 52, 52]
The total of the slice is 274
62 55 53 52 52

这是我想出的代码:

^{pr2}$

我对作业的最后一部分有问题:
使用while循环将切片中的所有元素显示在一行上,用制表符分隔。在

我使用的代码似乎可以正常工作,但它给了我一个错误消息:

我的输出

 80 76 79 75 75 77 77 71 66 50 53 52 
    Yes, 66 is in the list at index 8
    The largest element is 80
    The smallest element is 50
    Here is the slice [75, 77, 77, 71, 66]
    The total of the slice is 366
    75 77 77 71 66 Traceback (most recent call last):
      File "C:\Users\Isaiah\Desktop\chapter7\program7_1.py", line 41, in
    <module>
        main()
      File "C:\Users\Isaiah\Desktop\chapter7\program7_1.py", line 38, in main
        print(numList[4:-3][count], end=' ')
    IndexError: list index out of range

有人知道是什么问题吗?我是怎么解决的?在


Tags: ofthein元素列表indexis切片
2条回答

您想要打印numList的一个片段,它是numList[4:-3],如果假设len(numList)是10,那么len(numlist[4:-3])是3。在

while count < len(numList)将导致while循环在count=10时终止。但是,当count=3时,您试图打印numList[4:-3][count],这将抛出IndexError: list index out of range,因为{}只有3,所以它的索引是0,1,2。在

所以,只需将循环终止条件改为when count < len(numList[4:-3])

你真的可以用一行代码来实现这一点。在

反向排序列表:

>>> sorted(l , reverse = True)
[71, 70, 67, 66, 62, 55, 53, 52, 52, 52, 51, 50]

从索引4-8切片

^{pr2}$

总计切片

>>> sum(l[len(l)-8:len(l)-3])
274

相关问题 更多 >