从列表列表到列表列表

问题描述 投票:0回答:3

我有这样的列表:

first_list = [[ 1.        , 45.4,  9.1],
              [ 2.        , 45.5,  9.1],
              [ 2.        , 45.4,  9.2],
              [ 2.        , 45.4,  9.2],
              [ 3.        , 45.4,  9.1],
              [ 3.        , 45.4,  9.1],
              [ 3.        , 45.4,  9.1] ]

我想使用作品集功能HeatMapWithTime,为此,我需要根据每个子列表的第一项(1,。,2、3。ecc)对上面的数据进行分组:

new_list = [ [ [45.4, 9.1] ],                               # All coords for 1.
             [ [45.5, 9.1], [45.4, 9.2], [45.4, 9.2] ],     # All coords for 2.
             [ [45.4, 9.1], [45.4, 9.1], [45.4, 9.2] ] ]    # All coords for 3.

我该怎么做?

python list folium
3个回答
1
投票

假设列表按看起来的前几个元素排序,则可以使用itertools.groupby

itertools.groupby

0
投票

一种方法是首先对列表进行排序:

lst_data = sorted(first_list)

然后循环遍历,在拳头索引更改时创建一个新的ljst:

from itertools import groupby
from operator import itemgetter
[[i[1:] for i in v] for k,v in groupby(first_list, itemgetter(0))]

#[[[45.4, 9.1]],
# [[45.5, 9.1], [45.4, 9.2], [45.4, 9.2]],
# [[45.4, 9.1], [45.4, 9.1], [45.4, 9.1]]]

0
投票

我将为此使用字典,如果您需要将其作为列表使用,则可能希望将其放回列表,但是使用字典进行分组通常会有所帮助:

first_index = None
final_lst = []
for i in lst_data:
    if i[0] != first_index:
        final_lst.append([])
        first_index = i[0]
    final_lst[-1].append(i[1:])

输出:

first_list = [[ 1.        , 45.4,  9.1],
              [ 2.        , 45.5,  9.1],
              [ 2.        , 45.4,  9.2],
              [ 2.        , 45.4,  9.2],
              [ 3.        , 45.4,  9.1],
              [ 3.        , 45.4,  9.1],
              [ 3.        , 45.4,  9.1] ]
result = dict()
for group, *values in first_list:
    if group not in result:
        result[group] = [values]
    else:
        result[group].append(values)
print(result)
### if you want it back as a list:
result_list = [v for k,v in result.items()]
print(result_list)
© www.soinside.com 2019 - 2024. All rights reserved.