連線列表中的各種元素(list/tuple/string/array/tensor)的方法彙總
阿新 • • 發佈:2021-01-29
文章目錄
1、拼接列表中的列表/元組
>>>l1 = [[1,2,3],[4,5],[6,7,8,9]]
>>>ans1 = list(range(1,10))
>>>ans1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>l2 = [(1,2,3),(4,5),(6,7,8,9)]
>>>ans2 = tuple(range(1,10))
>> >ans2
(1, 2, 3, 4, 5, 6, 7, 8, 9)
這兩種型別的拼接方法一樣,都要用到itertools模組中的chain方法
>>>import itertools
>>>res1 = list(itertools.chain(*l1))
>>>res1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>res2 = tuple(itertools.chain(*l2))
>>>res2
(1, 2, 3, 4, 5, 6, 7, 8, 9)
2、拼接列表中的字串
>>>l3 = ['My','Name','Is','Jasmine','FENG']
>>>ans3 = ['MyNameIsJasmineFENG']
藉助字串內建的join方法,在字串之間插入''
>>>res3 = [''.join(l3)]
>>>res3
['MyNameIsJasmineFENG']
3、拼接列表中的ndarray/tensor
>>>import torch
>>>import numpy as np
>>>l4 = [np.array( [1,2]),np.array([2,3]),np.array([2,3,4])]
>>>ans4 = [np.array([1,2,2,3,2,3,4])]
>>>l5 = [torch.Tensor([1,2]),torch.Tensor([2,3]),torch.Tensor([2,3,4])]
>>>ans5 = [torch.Tensor([1,2,2,3,2,3,4])]
這兩種型別方法也一樣,都要用到各自模組中的hstack方法。
>>>res4 = np.hstack(l4)
>>>res4
array([1, 2, 2, 3, 2, 3, 4])
>>>res5 = torch.hstack(l5)
>>>res5
tensor([1., 2., 2., 3., 2., 3., 4.])
P.S. np.hstack
和torch.hstack
不僅僅可以接受元組作為引數,也可以接受列表作為引數