切片具有不同长度的子列表

时间:2016-07-06 13:06:38

标签: python list numpy slice

我有一份清单清单。每个子列表的长度在1到100之间变化。每个子列表包含一组数据中不同时间的粒子ID。我想在给定时间形成所有粒子ID的列表。要做到这一点,我可以使用类似的东西:

def overlaps (self, other_rect):
   return self.rect.colliderect(other_rect)

list2将包含列表中每个子列表的第一个元素。我想做的不只是第一个元素,而是1到100之间的每个元素。我的问题是每个子列表都不存在元素号100(或66或77或其他)。

是否有某种方法可以创建列表列表,其中每个子列表都是给定时间内所有粒子ID的列表。

我曾考虑过尝试使用numpy数组来解决这个问题,就好像这些列表的长度都相同,这一点都是微不足道的。我已经尝试在每个列表的末尾添加-1,以使它们具有相同的长度,然后屏蔽负数,但到目前为止这对我没有用。我将在给定时间使用ID列表来切片另一个单独的数组:

    list = [[1,2,3,4,5],[2,6,7,8],[1,3,6,7,8]]
    list2 = [item[0] for item in list]

5 个答案:

答案 0 :(得分:2)

lst = [[1,2,3,4,5],[2,6,7,8],[1,3,6,7,8]]
func =  lambda x: [line[x] for line in lst if len(line) > x]

func(3)
[4, 8, 7]
func(4)
[5, 8]

- 更新 -

func =  lambda x: [ (line[x],i) for i,line in enumerate(lst) if len(line) > x]
func(4)
[(5, 0), (8, 2)]

答案 1 :(得分:1)

您可以使用itertools.zip_longest。这将列出zip个列表,并在其中一个列表用尽时插入None

>>> lst = [[1,2,3,4,5],['A','B','C'],['a','b','c','d','e','f','g']]    
>>> list(itertools.zip_longest(*lst))
[(1, 'A', 'a'),
 (2, 'B', 'b'),
 (3, 'C', 'c'),
 (4, None, 'd'),
 (5, None, 'e'),
 (None, None, 'f'),
 (None, None, 'g')]

如果您不想要None元素,可以将其过滤掉:

>>> [[x for x in sublist if x is not None] for sublist in itertools.zip_longest(*lst)]
[[1, 'A', 'a'], [2, 'B', 'b'], [3, 'C', 'c'], [4, 'd'], [5, 'e'], ['f'], ['g']]

答案 2 :(得分:0)

如果您想要one-line forloop并且array,则可以执行此操作:

list2 = [[item[i] for item in list if len(item) > i] for i in range(0, 100)]

如果您想知道哪个ID来自哪个列表,您可以执行此操作:

list2 = [{list.index(item): item[i] for item in list if len(item) > i} for i in range(0, 100)]

list2会是这样的:

[{0: 1, 1: 2, 2: 1}, {0: 2, 1: 6, 2: 3}, {0: 3, 1: 7, 2: 6}, {0: 4, 1: 8, 2: 7},
 {0: 5, 2: 8}, {}, {}, ... ]

答案 3 :(得分:0)

您可以将numpy.nan附加到短名单中,然后创建一个numpy数组

import numpy
import itertools

lst = [[1,2,3,4,5],[2,6,7,8],[1,3,6,7,8,9]]
arr = numpy.array(list(itertools.izip_longest(*lst, fillvalue=numpy.nan)))

之后你可以照常使用numpy切片。

print arr
print arr[1, :]   # [2, 6, 3]
print arr[4, :]   # [5, nan, 8]
print arr[5, :]   # [nan, nan, 9]

答案 4 :(得分:0)

方法#1

可以建议一种近乎*矢量化的方法,即根据新订单和拆分创建ID,如此 -

def position_based_slice(L):

    # Get lengths of each element in input list
    lens = np.array([len(item) for item in L])

    # Form ID array that has *ramping* IDs within an element starting from 0
    # and restarts with a new element at 0
    id_arr = np.ones(lens.sum(),int)
    id_arr[lens[:-1].cumsum()] = -lens[:-1]+1

    # Get order maintained sorted indices for sorting flattened version of list
    ids = np.argsort(id_arr.cumsum(),kind='mergesort')

    # Get sorted version and split at boundaries decided by lengths of ids
    vals = np.take(np.concatenate(L),ids)
    cut_idx = np.where(np.diff(ids)<0)[0]+1
    return np.split(vals,cut_idx)

*开头有一个循环理解,但是只是要收集列表输入元素的长度,它对总运行时间的影响应该是最小的。

示例运行 -

In [76]: input_list = [[1,2,3,4,5],[2,6,7,8],[1,3,6,7,8],[3,2]]

In [77]: position_based_slice(input_list)
Out[77]: 
[array([1, 2, 1, 3]), # input_list[ID=0]
 array([2, 6, 3, 2]), # input_list[ID=1]
 array([3, 7, 6]),    # input_list[ID=2]
 array([4, 8, 7]),    # input_list[ID=3]
 array([5, 8])]       # input_list[ID=4]

方法#2

这是另一种创建2D数组的方法,它更容易索引并追溯到原始输入元素。这使用NumPy广播和布尔索引。实现看起来像这样 -

def position_based_slice_2Dgrid(L):

    # Get lengths of each element in input list
    lens = np.array([len(item) for item in L])

    # Create a mask of valid places in a 2D grid mapped version of list
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape,-1,dtype=int)
    out[mask] = np.concatenate(L)
    return out

示例运行 -

In [126]: input_list = [[1,2,3,4,5],[2,6,7,8],[1,3,6,7,8],[3,2]]

In [127]: position_based_slice_2Dgrid(input_list)
Out[127]: 
array([[ 1,  2,  3,  4,  5],
       [ 2,  6,  7,  8, -1],
       [ 1,  3,  6,  7,  8],
       [ 3,  2, -1, -1, -1]])

因此,现在输出的每一列都对应于基于ID的输出。

相关问题