我的导师没有费心明确指定索引号来访问列表中的特定元素.这对我来说似乎很奇怪,我相信这也会影响代码的可读性.有人能解释一下我导师的代码是如何完美运行的吗?不过我明白了逻辑.

100

score_student = input("Enter the score of each student: ")
list_of_marks = []
list_of_marks = score_student.split(" ")
print(list_of_marks)
index_count = 0
for item in range(1, len(list_of_marks)):
    if list_of_marks[index_count] < list_of_marks[item]:
        index_count = item
    else:
        continue
print("Largest score in class = " + list_of_marks[index_count])

100

student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
  student_scores[n] = int(student_scores[n])
print(student_scores)
highest_score = 0
for score in student_score:
     if score > highest_score:
          highest_score = score
print(f"Highest score in class:{highest_score} ")

推荐答案

The explanation

在Python中,我们通常避免迭代索引,而是直接迭代各种iterable对象的元素.这就是你的导师在这里做的.

迭代元素意味着无论迭代的数据 struct 类型如何,相同的代码都可以工作,而使用索引的代码仅限于使用索引的代码.

Sample data structures with and without indices

这些数据 struct 支持迭代和整数索引,因此您的代码也可以工作:

  • 列表
  • 元组
  • 字符串(迭代字符)

这些数据 struct 支持迭代,但不支持整数索引:

  • 集合
  • 词典*
  • 发电机

这只是一个简短的例子列表,但还有更多的例子.

When you also need indices, use enumerate

有时在代码中,您可能也需要索引,以及您正在迭代的项.回到原来的for i in range(1, len(my_list)):可能很诱人,但最好不要这样做,因为你会带回my_list实际上必须支持索引的限制.Python中针对该需求的首选解决方案是使用enumerate():

for i, item in enumerate(something_iterable):
    # do stuff with item, knowing that it was in position i during iteration

Iterating over dicts

Dicts got a star是我列出的可重用项列表,因为迭代Dicts更复杂,因为它们包含键/值对,而不是简单的项.

我认为在这里讨论细节已经超出了你的问题范围,但请看https://realpython.com/iterate-through-dictionary-python/以获得对该主题的体面介绍,或者只需在谷歌上"用Python迭代dicts"以获得更多关于该主题的好页面.

Python相关问答推荐

时间序列分解

Pytest两个具有无限循环和await命令的Deliverc函数

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

将数据框架与导入的Excel文件一起使用

Python虚拟环境的轻量级使用

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

如何获得每个组的时间戳差异?

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

如何在表中添加重复的列?

mypy无法推断类型参数.List和Iterable的区别

旋转多边形而不改变内部空间关系

将标签移动到matplotlib饼图中楔形块的开始处

如何使用使用来自其他列的值的公式更新一个rabrame列?

使用类型提示进行类型转换

从嵌套极轴列的列表中删除元素

如何在一组行中找到循环?

裁剪数字.nd数组引发-ValueError:无法将空图像写入JPEG

如何写一个polars birame到DuckDB

Pandas 删除只有一种类型的值的行,重复或不重复

解析CSV文件以将详细信息添加到XML文件