I have a list of temperatur measurement:
temp = [ [39, 38.5, 38], [37,37.5, 36], [35,34.5, 34], [33,32.5, 32], [31,30.5, 30], [29,28.5, 28], [27,26.5,26] ]
every value is recorded every 5 hour over several days. First day is first list of temp: [39, 38.5, 38],
second day is second list of temp: [37, 37.5, 36]
etc.
What I always do is, I loop over the 'temp' and calculate the time difference between the values and save this as list in time. (The time difference is always 5h)
time=[]
for t in temp:
for i,val in enumerate(t):
i=i*5
time.append(i)
print time
The output looks like this:
time: [0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10]
But I want to get sublists of every day, like:
time: [ [0, 5, 10] , [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10] ]
What`s wrong in my code?
You keep appending to the same list, you should create a new list for every day.
time=[]
for t in temp:
day_list = [] # Create a new list
for i,val in enumerate(t):
i=i*5
day_list.append(i) # Append to that list
time.append(day_list) # Then append the new list to the output list
print time
For a list comprehension:
time = [[i*5 for i, val in enumerate(t)] for t in temp]
You are appending all timestamp to a single-level list, so that's what your algorithm outputs.
Here is one way to get a list of lists:
>>> [list(range(0, len(t) * 5, 5)) for t in temp]
[[0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10]]
This correctly deals with sublists of temp
potentially having different lengths.
If you want the exact same thing in each list, do this:
time = [[0,5,10] for _ in temp]
To account for variable sublist length:
In python 2
time = [range(0, len(i)*5, 5) for i in temp]
In python 3, must materialize range:
time = [list(range(0, len(i)*5, 5)) for i in temp]
You have to create a temporary sub list and then append that sublist to the actual list to get a bunch of sublists within a list
temp = [ [39, 38.5, 38], [37,37.5, 36], [35,34.5, 34], [33,32.5, 32], [31,30.5, 30], [29,28.5, 28], [27,26.5,26] ]
time=[]
for t in temp:
l = []
for i,val in enumerate(t):
i=i*5
l.append(i)
if len(l) == 3:
time.append(l)
print time
使用列表理解,您可以在一行中完成:
time = [[i*5 for i, val in enumerate(t)] for t in temp]
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.