Python 通过循环创建列表
我试图通过循环转换创建新的列表,但只有最后的转换被放入列表中,因为转换变量始终保持不变Python 通过循环创建列表,python,list,for-loop,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 = [c
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
每次迭代都要创建一个新的列表对象:
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上循环:
您还可以使用以下工具一次性生成整个华氏温度
:
最后一行的快速演示:
>>> 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]
在开始循环之前创建目标列表,并将转换后的值附加到循环中 此外,您还有
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
使用此任务的列表理解:
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]
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
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
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]