通过循环创建列表

时间:2014-11-26 15:53:31

标签: python list for-loop

我正在尝试通过循环转换创建新列表,但只有最终转换才会列入列表,因为转换变量始终保持不变

celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]

number = 0

for i in range(1,len(celsius_temps)+1):
    conversion = celsius_temps[0+number]*1.8000 + 32
    number += 1
    fahrenheit_temps = [conversion]


print fahrenheit_temps

4 个答案:

答案 0 :(得分:8)

每次迭代都要创建一个新的列表对象:

fahrenheit_temps = [conversion]

您在循环外创建一个列表对象,并将结果追加到:

number = 0
fahrenheit_temps = []

for i in range(1,len(celsius_temps)+1):
     conversion = celsius_temps[0+number] * 1.8 + 32
     number += 1
     fahrenheit_temps.append(conversion)

你真的想要清理那个循环;您没有使用i,只能使用number生成fahrenheit_temps = [] for number in range(len(celsius_temps)): conversion = celsius_temps[number] * 1.8 + 32 fahrenheit_temps.append(conversion)

celcius_temps

或者更好的是,只需直接遍历fahrenheit_temps = [] for temp in celsius_temps: conversion = temp * 1.8 + 32 fahrenheit_temps.append(conversion)

fahrenheit_temps

您还可以使用list comprehension一次生成整个fahrenheit_temps = [temp * 1.8 + 32 for temp in celsius_temps]

>>> celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]
>>> [temp * 1.8 + 32 for temp in celsius_temps]
[77.36, 62.24, 88.52, 75.02, 82.4, 72.5, 67.28]

最后一行的快速演示:

{{1}}

答案 1 :(得分:1)

celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]
fahrenheit_temps = []

for t in celsius_temps:
     fahrenheit_temps.append(t*1.8000 + 32)

print fahrenheit_temps

答案 2 :(得分:1)

在开始循环之前创建目标列表,并将转换后的值附加到循环中。

此外,您有i作为计数器,并使用名为number的额外计数器。这是多余的。只需迭代元素。

celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]

fahrenheit_temps = []
for celsius_temp in celsius_temps:
     fahrenheit_temps.append(celsius_temp * 1.8 + 32)


print fahrenheit_temps

答案 3 :(得分:1)

使用列表推导执行此任务:

celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]
fahrenheit_temps = [item*1.8000 + 32 for item in celsius_temps]
print fahrenheit_temps

>>> [77.36, 62.24, 88.52, 75.02, 82.4, 72.5, 67.28]
相关问题