[英]quick question on printing results in python
我目前正在嘗試使用 python 中的 for 循環打印列表的結果,但我希望最后一個數字打印一個空格,然后是換行符。 例如。
hourly_temperature = [90, 92, 94, 95]
for num in hourly_temperature:
print(num, '-> ', end= '')
我得到90 -> 92 -> 94 -> 95 ->
但我想要90 -> 92 -> 94 -> 95
我試過使用len
和range
和if
else
語句,但我沒有真正工作。
如果要使用 for 循環,可以遍歷除最后一個元素之外的每個元素,然后手動打印最后一個元素,如下所示:
for num in hourly_temperature[:-1]:
print(num, '->', end='')
print(num[-1])
不過,使用 join 可能更簡單,例如:
strs = [str(x) for x in hourly_temperature] #convert values to str
print('->'.join(strs))
這會將您的列表轉換為字符串,每兩個元素之間有一個“->”。
嘗試這個:
' -> '.join(str(element) for element in hourly_temperature)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.