2021-03-20
閱讀量:
814
Python 如何在列表添加元素
一、追加單個(gè)值: append() 方法
追加單個(gè)元素:
>>> list = ['crazyit', 20, -2]
>>> list.append('fkit')
>>> print(list)
['crazyit', 20, -2, 'fkit']
二、追加元組、列表等:extend() 方法
追加元組中的所有元素:
>>> b_list = ['a', 30]
>>> b_list.extend((-2, 3.1))
>>> print(b_list)
['a', 30, -2, 3.1]
>>> a_list = (3.4, 5.6)
>>> b_list.extend(a_list)
>>> print(b_list)
['a', 30, -2, 3.1,3.4, 5.6]
三、列表中間增加元素:insert() 方法
>>> c_list = [1, 2, 3, 4, 5]
>>> c_list.insert(3, 'CRAZY' )
>>> print(c_list)
[1, 2, 3, 'CRAZY', 4, 5]
>>> c_list.insert(3, tuple('crazy'))
>>> print(c_list)
[1, 2, 3, ('c', 'r', 'a', 'z', 'y'), 'CRAZY', 4, 5] # 在索引3處插入元組,元組被當(dāng)成一個(gè)元素






評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論
0條評(píng)論