python-3.x - for 循环中的下划线 "_"

标签 python-3.x

这个问题在这里已经有了答案:





What is the purpose of the single underscore "_" variable in Python?

(5 个回答)



Trying to understand Python loop using underscore and input

(4 个回答)


3年前关闭。




我正在检查一个关于黑客等级的解决方案,我正在解决一个问题,要求从输入中打印得分第二高的人的姓名,该输入必须首先转换为嵌套列表。

我理解代码中的所有逻辑和大部分代码,但是为什么 for 循环中的下划线(_)。如果有不同的概念,请解释代码。

marksheet = []
for _ in range(0,int(input())):
    marksheet.append([input(), float(input())])

second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

最佳答案

当函数、生成器或元组的返回值要被丢弃时,使用下划线作为变量名是 Pythonic 的约定。

在您的示例中,for 中的代码循环不使用 range(0,int(input())) 生成的值,所以使用下划线是有道理的,因为很明显循环不打算使用它。

关于python-3.x - for 循环中的下划线 "_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570364/

相关文章:

python - 如何在缩进中使用制表符和空格不一致? | python

python-3.x - 如果目录不包含 __init__.py 文件,pylint 会引发错误

Python 3 - 模块未找到错误 : No module named 'xgboost'

python - RuntimeError:OrderedDict在迭代过程中发生了突变(Python3)

python - 将 QuadgramCollat​​ionFinder 转换为 PentagramCollat​​ionFinder

python - pandas.read_json() 未按预期工作

python - 使正则表达式准确匹配点文件

python-3.x - 如何更改 altair 中 geo_shape 的限制(python vega-lite)

python - 如何从给定的数据中找到Python中的公共(public)数据对

python-3.x - 在 django doctesting 时设置测试选项