繁体   English   中英

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

[英]Get first few elements of tuples from list of list of tuples

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

[[(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中完成?

[[(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,)]]

只需使其非常简单,然后遍历嵌套列表,然后执行所需的操作即可:

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,)]]

即使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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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