List添加元素_Python_CodingPark編程公園

文章介紹

內容概要:list 添加元素的方法包含 append()、extend() 、insert()

append()函數

append()函數將新元素追加到列表末尾

舉個例子-1

In [1]: a = [1, 2, 3, 4, 5]
In [2]: a.append(6)
In [3]: a
Out[3]: [1, 2, 3, 4, 5, 6]

結果:
把一個字符,追加到了列表末尾


舉個例子-2

import os
from tqdm import tqdm
from pyhanlp import *


def getDataset():
    def readtxt(path):
        with open(path, 'r', encoding='gbk') as fr:
            content = fr.read()
            return content

    filepath = '/Users/atom-g/Desktop/DanMuAnalyzePark/FuDanUniversity_data/test_corpus/corpus/'
    dirs = os.listdir(filepath)
    # print(dirs)

    dataset = []
    for fileNum in tqdm(dirs):
        text = readtxt(filepath + fileNum)
        text_process = HanLP.segment(text)
        text_list = [(str(i.word), str(i.nature)) for i in text_process]
        # print(text_list)

        file = []
        for i in text_list:
            if i[1] != 'w' and len(i[0]) > 1:
                file.append(i[0])
        dataset.append(file)

    return dataset

    # print(dataset)

結果:
把一個列表,追加到了列表末尾

總結

append()函數可以吧你想要的內容(包括單個或整體),追加到末尾


extend()函數

extend()函數可以將另一個列表中的元素 逐一 添加到指定列表中

舉個例子

對比 append() 與 extend()

使用append()函數:


In [1]: a = [1, 2]
In [2]: b = [3, 4]
In [3]: a.append(b)
In [4]: a
Out[4]: [1, 2, [3, 4]]

使用extend()函數的效果:


In [1]: a = [1, 2]
In [2]: b = [3, 4]
In [3]: a.extend(b)
In [4]: a
Out[4]: [1, 2, 3, 4]


insert()函數

insert()函數將新元素添加到 指定索引號 前面

舉個例子-1

再來一個元素’0’,它比’1’要小,想讓它添加到列表的最前面。可以用insert()函數實現:

  insert(index, object)		  它接受兩個參數,第一個參數是索引號,第二個參數是待添加的新元素

注意:第一個 0 是索引號,後一個 0 是添加的新元素。


In [1]: a = [1, 2, 3, 4, 5]
In [2]: a.insert(0, 0)
In [3]: a
Out[3]: [0, 1, 2, 3, 4, 5]

舉個例子-2


In [1]: a = [1, 2, 3, 4, 5]
In [2]: a.insert(1, 6)
In [3]: a
Out[3]: [1, 6, 2, 3, 4, 5]

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章