简体   繁体   中英

Creating a list through looping

I'm trying to make new list through looping conversions, but only the final conversion gets put in list because conversion variable always stays the same

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

You are creating a new list object each iteration:

fahrenheit_temps = [conversion]

You'd create an empty list object outside the loop and append results to that:

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)

You really want to clean up that loop though; you are not using i where you could simply produce number with it:

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

or better still, just loop over celcius_temps directly :

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

You could also produce the whole fahrenheit_temps in one go with a list comprehension :

fahrenheit_temps = [temp * 1.8 + 32 for temp in celsius_temps]

A quick demo of that last line:

>>> 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]
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

Create your target list before you start the loop and append the converted values in the loop.

Additionally, you have i as a counter and you use an extra counter called number . That's superfluous. Just iterate over the elements.

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

Use the list comprehension for this task:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM