从元组列表列表中获取元组的前几个元素

时间:2017-12-08 06:16:24

标签: python python-3.x

我有一个元组列表列表的结构,如: -

[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]

我基本上想要从中获取2个元组列表。前两列的一个元组,第三列的另一个元组。 期望的输出: -

[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]

&安培;&安培;

[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]

如何在python中完成?

3 个答案:

答案 0 :(得分:4)

[[(a, b) for a, b, *c in r] for r in arr]
# => [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]

[[tuple(c) for a, b, *c in r] for r in arr]
# => [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]

回应评论:

def slice_nested_array(arr, start, stop=None, step=1):
    if stop is None:
        stop = len(arr[0][0])
    return [[tuple(l[start:stop:step]) for l in r] for r in arr]

slice_nested_array(arr, 0, 2)
# => [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]
slice_nested_array(arr, 2)
# => [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]

答案 1 :(得分:0)

保持简单,并循环嵌套列表,并采取您所需的:

lst = [[(1, 1, 96),
        (1, 2, 95),
        (0, 5, 23),
        (0, 6, 22)],
       [(2, 1, 145),
        (1, 2, 144),
        (10, 3, 143),
        (2, 4, 142)]]

first = []
second = []

for l in lst:
    for tup in l:
        first.append(tup[:-1])
        second.append((tup[-1],))

print(first)
# [(1, 1), (1, 2), (0, 5), (0, 6), (2, 1), (1, 2), (10, 3), (2, 4)]
print(second)
# [(96,), (95,), (23,), (22,), (145,), (144,), (143,), (142,)]

或者列表推导:

first = [tup[:-1] for l in lst for tup in l]
second = [(tup[-1],) for l in lst for tup in l]

然后将这些列表分别变为2个子列表:

sublen = len(lst[0])

def split_lists(l, s):
    return [l[i:i+s] for i in range(0, len(l), s)]

print(split_lists(first, sublen))
# [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]

print(split_lists(second, sublen))
# [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]

答案 2 :(得分:0)

尽管Amadan的答案运作良好,但我想编写一个通用函数来实现所需的结果。这是最终的代码: -

def fn(data, one_shot_columns, scalar_columns):
     zipped=list(zip(*data)) 
     one_shot_zipped=[zipped[i] for i in one_shot_columns] 
     one_shot=list(zip(*one_shot_zipped)) 
     scalar_zipped=[zipped[i] for i in scalar_columns] 
     scalar=list(zip(*scalar_zipped)) 
     return (one_shot,scalar)

使用如下: -

hist_oneshot,hist_scalar = fn(hist,[0,1],[2])