我只是在学习Python,并且正在尝试将范围与枚举结合起来。我尝试了一些如:
students = ("James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Donald","Mark","Paul","Steven","Andrew","Kenneth","George","Joshua","Kevin","Brian","Edward","Mary","Patricia","Jennifer","Elizabeth","Linda","Barbara","Susan","Jessica","Margaret","Sarah","Karen","Nancy","Betty","Lisa","Dorothy","Sandra","Ashley","Kimberly","Donna","Carol","Michelle","Emily","Amanda","Helen","Melissa")
print("The gold medal goes to:",students[0])
print("The silver medal goes to:",students[1])
print("The bronze medal goes to:",students[2])
print("All winners in order:")
for index, student in enumerate(students):
for students in range(3,51):
place=str(index+1)
print(place,student.title())
这给了我一个错误,我试过这个:
.psuedo-background-img-container {
position: relative;
width:400px;
height: 200px;
}
.psuedo-background-img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
只打印每个名字50次。 我只是一名学生,所以感谢任何帮助!
答案 0 :(得分:0)
您的示例不需要使用range
。为了了解您的摘要中出了什么问题,请考虑以下代码:
>>> for index, student in enumerate(students):
... print(index, student)
...
此打印:
0 James
1 John
2 Robert
...
49 Melissa
enumerate
具有两个参数:
它返回两件事:
len(your_array)-1
)请注意您的第一个代码段如何包含for index, student in enumerate(students in range(3,51)):
,尤其是students in range(3,51)
表达式。因为 that 并不紧跟for
的前面,所以它没有像您希望的那样遍历范围,而是将其作为条件。而且由于students
是您代码中的元组,因此 not 不在range(3,51)
内,并且此表达式将返回False。由于无法调用enumerate(False)
,因为False不是数组,所以会收到错误TypeError: 'bool' object is not iterable
。
在第二个片段中,您遍历了整个枚举,但是每个名称实际上被打印了48次(51-3 = 48),而被多次打印的原因是因为内部for
语句具有index
和student
元素,但是每次将students
设置为3、4,以50为上限(但不包括51)时,都会打印它们。顺便说一句,请不要在此处重新分配students
,否则它将用数字代替您的学生组。
相反,您应该切出所需的学生元组的一部分,并指定要打印的第一个索引,然后将其作为参数传递给enumerate
,因此,您的情况是:enumerate(students[3:], 3)
。特别是,您以此打印的索引将从三个开始,不是为零。
然后您的代码变为:
students = ("James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Donald","Mark","Paul","Steven","Andrew","Kenneth","George","Joshua","Kevin","Brian","Edward","Mary","Patricia","Jennifer","Elizabeth","Linda","Barbara","Susan","Jessica","Margaret","Sarah","Karen","Nancy","Betty","Lisa","Dorothy","Sandra","Ashley","Kimberly","Donna","Carol","Michelle","Emily","Amanda","Helen","Melissa")
print("The gold medal goes to:",students[0])
print("The silver medal goes to:",students[1])
print("The bronze medal goes to:",students[2])
print("All winners in order:")
for index, student in enumerate(students[3:], 3):
place=str(index+1)
print(place,student.title())
这将打印预期的输出:
4 Michael
5 William
6 David
...
50 Melissa