[英]Python: Output format of a list
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. 几天内每5个小时记录一次每个值。 First day is first list of temp:
[39, 38.5, 38],
second day is second list of temp: [37, 37.5, 36]
etc. 第一天是温度的第一项列表:
[39, 38.5, 38],
第二天是温度的第二项列表: [37, 37.5, 36]
。
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)
(时差始终为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. 这可以正确处理可能具有不同长度的
temp
子列表。
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 在python 2中
time = [range(0, len(i)*5, 5) for i in temp]
In python 3, must materialize range: 在python 3中,必须实现范围:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.