python - 如何使用循环当前引用的位置更新变量?
问题描述
我有一个输入列表,我正在使用 for 循环搜索每个值以查找最高温度以及列表中的哪个位置。
我已经完整地编写了代码,除了我不知道我会用我的循环正在查看的当前位置更新 best_position 。
# set best_position to position
best_position =
这就是我挣扎的地方。
# initialise the input with a non-empty list - Do NOT change the next line
temperatures = [4.7, 3, 4.8]
# set best_position to 0
best_position = 0
maxtemp = temperatures[0]
# for each position from 1 to length of list – 1:
for i in temperatures:
# if the item at position is better than the item at best_position:
if maxtemp<i:
maxtemp = i
# set best_position to position
best_position =
# print best_position
print(best_position, ": 00")
解决方案
使用enumerate
功能:
https://docs.python.org/3/library/functions.html#enumerate
# initialise the input with a non-empty list - Do NOT change the next line
temperatures = [4.7, 3, 4.8]
# set best_position to 0
best_position = 0
maxtemp = temperatures[0]
# for each position from 1 to length of list – 1:
for pos, t in enumerate(temperatures):
# if the item at position is better than the item at best_position:
if maxtemp<t:
maxtemp = t
# set best_position to position
best_position = pos
# print best_position
print(best_position, ": 00")
或者,您可以这样做:
max_temp = max(temperatures)
best_pos = temperatures.index(max_temp)
print(best_pos, ": 00")
推荐阅读
- php - 仅在后端显示来自 WooCommerce 的“尾随零”
- git - 将功能齐全的 git 添加到 yocto build
- autocomplete - 不尊重 TextArea 上的自动完成功能
- php - Twig 基于整数值生成
- c# - C#:如何优雅地获取所有后代 XElement,包括 XElement 的根元素?
- database - 多重完全连接在 PostgreSQL 中不起作用
- flutter - Flutter initState() 返回'_debugLifecycleState == _StateLifecycle.created':不正确
- javascript - 如何通过 JavaScript 对 html bootstrap DataTable 中的 firestore 数据进行排序?
- reactjs - ReactJS:对 fetch 的访问已被 CORS 策略阻止
- c++ - 每次我运行此代码时,我的 Raspberry-pi 3b+ 都会重新启动