温度的Python循环

新手上路,请多包涵

我是第一次学习 python,我的作业要求我:

编写一个循环来打印 hourly_temperature 中的所有元素。用空格包围的 -> 分隔元素。给定程序的示例输出:

>  90 -> 92 -> 94 -> 95
>
> ```
>
> 注意:95 后跟一个空格,然后是换行符。

播放后我遇到了困难,发现编码答案为:

hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list temps = []

if Htemp >= 0: for i in hourly_temperature: #question on i and appends i temps.append(i) temps.append(‘->’) Htemp -= 1 continue temps.pop() for s in temps: #question here print(s,“, end=”) continue print(“)

”`

我的问题是关于我用#question 标记的for 循环。

我想知道 is 使代码工作的目的是什么。

原文由 Alita 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 613
2 个回答

我相信这里的很多人都会为您提供“Pythonic”单行代码,以输出您需要的内容。但我认为你正处于需要学习如何逻辑编码而不是如何成为 Pythonic 的阶段。

您给出的示例在任何语言中都是混乱且不优雅的。

以下是我如何使用适合初学者的简单逻辑对您的作业进行编码。希望这比简短的一行更有帮助。

 hourly_temperature = [90, 92, 94, 95]

# Start with an empty string
s = ""

# Step through each temperature in the list
for t in hourly_temperature:

    # If the string contains a number, then we need to add ->
    # before the next number.
    if s != "":
        s += "-> "

    # Add the temperature and a space
    s += str(t) + " "

# Print the string we have just built
print(s)

另一种常见的实现结果的方法是不用担心在循环过程中检查“->”是否需要加前缀。相反,始终在前缀“->”并在末尾删除错误的。这对于大循环来说效率稍微高一些。

 hourly_temperature = [90, 92, 94, 95]

s = ""
for t in hourly_temperature:
    s += " -> " + str(t)

# At this stage, s contains " -> 90 -> 92 -> 94 -> 95" so we need to remove the first ->
# We do this by keeping everything from character 4 onwards
print(s[4:])

原文由 Thane Brooker 发布,翻译遵循 CC BY-SA 4.0 许可协议

i takes each value of hourly_temperature , as s takes the value of each element in temps .

这是一种使用分隔符连接值的非常复杂的方法。最好使用 str.join

 hourly_temperature = [90, 92, 94, 95]
print(' -> '.join(map(str, hourly_temperature)))

原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题