關于python列表增加元素的三種操作方法

這篇文章主要介紹了關于python列表增加元素的幾種操作方法,主要有insert方法,extend方法和append方法,每種方法給大家介紹的非常詳細,需要的朋友可以參考下

1、insert方法,該方法包含兩個參數,第一個參數為插入的位置參數,第二個參數為插入內容文章源自四五設計網-http://www.wasochina.com/43752.html

1
2
3
4
a = [0,0,0]
b = [1,2,3]
a.insert(0,b)
print a

輸出:文章源自四五設計網-http://www.wasochina.com/43752.html

[[1, 2, 3], 0, 0, 0]文章源自四五設計網-http://www.wasochina.com/43752.html

2、extend方法,該方法的參數為一個列表,將該指數所指定到的列表插入到原列表中文章源自四五設計網-http://www.wasochina.com/43752.html

1
2
3
4
a = [0,0,0]
b = [1,2,3]
a.extend(b)
print a

輸出:文章源自四五設計網-http://www.wasochina.com/43752.html

1
[0, 0, 0, 1, 2, 3]

3、append方法,該方法后面只能帶上一個參數文章源自四五設計網-http://www.wasochina.com/43752.html

1
2
3
a = [0,0,0]
a.append(1)
print a

輸出:文章源自四五設計網-http://www.wasochina.com/43752.html

1
[0, 0, 0, 1]

補充:下面看下Python列表-添加元素文章源自四五設計網-http://www.wasochina.com/43752.html

末尾添加元素文章源自四五設計網-http://www.wasochina.com/43752.html

1
2
3
4
names = ['John','Thomas','Jack','Tony']?
print(names)?
# 在末尾添加元素?
names.append('Bill')?print(names)

程序輸出文章源自四五設計網-http://www.wasochina.com/43752.html

1
2
['John', 'Thomas', 'Jack', 'Tony']
['John', 'Thomas', 'Jack', 'Tony', 'Bill']

插入元素

1
2
3
4
5
names = ['John','Thomas','Jack','Tony']?
print(names)
?# 在列表中插入元素
??names.insert(0,'Bill')
???print(names)

程序輸出

1
2
['John', 'Thomas', 'Jack', 'Tony']
['Bill', 'John', 'Thomas', 'Jack', 'Tony']

總結

以上所述是小編給大家介紹的python列表增加元素的幾種操作方法,希望對大家有所幫助。

我的微信
微信掃一掃
weinxin
我的微信
惠生活福利社
微信掃一掃
weinxin
我的公眾號
 
  • 本文由 四五設計網小助手 發表于 2024年3月27日10:23:12
  • 轉載請務必保留本文鏈接:http://www.wasochina.com/43752.html

發表評論

匿名網友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖動滑塊以完成驗證