0

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?

5 Answers 5

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

@ parchment: Thank you! Can i write the same with a list comprehension?
2

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.

1 Comment

Yeah, this is probably most what the original asker wants.
0

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

Comments

0

With list comprehension, you can do it in one line:

time = [[i*5 for i, val in enumerate(t)] for t in temp]

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.