Python 如何使用while循环将切片中的所有元素显示在由制表符分隔的一行上
这是我的家庭作业: 编写一个创造性的程序,如下所示,以展示您对Python列表的理解: 从空列表开始。 使用循环将12个介于50和80之间(含50和80)的随机整数添加到列表中。 按从高到低的降序排列列表。 使用循环将已排序的列表元素打印在一行上,行之间用单个空格分隔。 确定66是否在列表中,并生成一些适当的输出。参见示例输出。 打印列表中最大的元素和列表中最小的元素。 将索引为4到8的五个元素切掉,并分配给一个变量。 打印切片。 打印此切片中所有五个元素的总和。 使用while循环将切片中的所有元素显示在由选项卡分隔的一行上 样本输出 这是我想出的代码:Python 如何使用while循环将切片中的所有元素显示在由制表符分隔的一行上,python,while-loop,slice,Python,While Loop,Slice,这是我的家庭作业: 编写一个创造性的程序,如下所示,以展示您对Python列表的理解: 从空列表开始。 使用循环将12个介于50和80之间(含50和80)的随机整数添加到列表中。 按从高到低的降序排列列表。 使用循环将已排序的列表元素打印在一行上,行之间用单个空格分隔。 确定66是否在列表中,并生成一些适当的输出。参见示例输出。 打印列表中最大的元素和列表中最小的元素。 将索引为4到8的五个元素切掉,并分配给一个变量。 打印切片。 打印此切片中所有五个元素的总和。 使用while循环将切片中的所
import random
def main():
numList = []
for nums in range(12):
numList.append(random.randint(50, 80))
for nums in numList:
print(nums, end=' ')
print()
if 66 in numList:
print('Yes, 66 is in the list at index', numList.index(66))
else:
print('No, 66 is not in the list')
print('The largest element is', max(numList))
print('The smallest element is', min(numList))
print('Here is the slice', numList[4:-3])
print('The total of the slice is', sum(numList[4:-3]))
count = 0
while count < len(numList):
print(numList[4:-3][count], end=' ')
count += 1
main()
我在本任务的最后一部分遇到问题:
使用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
有人知道问题是什么吗?我是如何解决的?您可以通过一行程序真正实现这一点 反向排序列表:
>>> sorted(l , reverse = True)
[71, 70, 67, 66, 62, 55, 53, 52, 52, 52, 51, 50]
从索引4-8切片
>>> l[len(l)-8:len(l)-3]
[62, 55, 53, 52, 52]
总和切片
>>> sum(l[len(l)-8:len(l)-3])
274
您想要打印numList的一个片段,它是numList[4:-3],如果假设lennumList是10,那么lennumList[4:-3]是3 while count
因此,只要将循环终止条件更改为count
>>> sum(l[len(l)-8:len(l)-3])
274