gpt4 book ai didi

Python:使用for循环将int列表修改为str列表

转载 作者:行者123 更新时间:2023-11-30 23:35:13 26 4
gpt4 key购买 nike

def temperature(weather):
'''(list of ints) -> list of strs
Modify and return list, replacing each temp in list for weather condition.
Hot being over 25 degrees, and cool being under.
'''

所以,如果我运行 temp([24, 29, 11]),我希望它返回 ['cool', 'hot', 'cool']。

这就是我得到的。我想我正在创建一个新列表而不是修改它。如何修改列表而不是使用 for 循环创建新列表?

temp =[]
for degrees in weather:
if degrees > 25:
temp = temp + ['hot']
else:
temp = temp + ['cool']
return temp

最佳答案

虽然修改输入列表通常是一个坏主意,但如果您确实想这样做,请使用enumerate来获取索引和元素访问符号来更改列表内容:

for index, degrees in enumerate(weather):
if degrees > 25:
weather[index] = 'hot'
else:
weather[index] = 'cold'

如果您制定新列表,请不要说

temp = temp + [whatever]

这会创建 temp 的副本来附加新项目,并且可能会将性能降低到二次时间。相反,使用

temp += [whatever]

temp.append(whatever)

两者都会修改temp

关于Python:使用for循环将int列表修改为str列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17507892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com