簡體   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