繁体   English   中英

Python:列表的输出格式

[英]Python: Output format of 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] ]

几天内每5个小时记录一次每个值。 第一天是温度的第一项列表: [39, 38.5, 38],第二天是温度的第二项列表: [37, 37.5, 36]

我总是做的是,我遍历“温度”并计算值之间的时间差,并将其保存为时间列表。 (时差始终为5h)

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

输出看起来像这样:

time: [0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10, 0, 5, 10]

但是我想获取每天的子列表,例如:

time: [ [0, 5, 10] , [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10], [0, 5, 10] ]

我的代码有什么问题?

您不断追加到同一列表,应该每天创建一个新列表。

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

对于列表理解:

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

您将所有时间戳附加到一个单级列表中,因此这就是算法输出的结果。

这是获取列表列表的一种方法:

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

这可以正确处理可能具有不同长度的temp子列表。

如果您希望每个列表中的内容完全相同,请执行以下操作:

time = [[0,5,10] for _ in temp]

要考虑可变子列表的长度:

在python 2中

time = [range(0, len(i)*5, 5) for i in temp]

在python 3中,必须实现范围:

time = [list(range(0, len(i)*5, 5)) for i in temp]

您必须创建一个临时子列表,然后将该子列表附加到实际列表中,以获得列表中的一堆子列表。

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.

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