關(guān)于操作 Python 列表,最常見問答Top10

列表是最常用的數(shù)據(jù)類型之一,本文整理了 StackOverflow 上關(guān)于列表操作被訪問最多的10個問答,如果你在開發(fā)過程中遇到這些問題,不妨先思考一下如何解決。


1、迭代列表時如何訪問列表下標索引


普通版:


items = [8, 23, 45]

for index in range(len(items)):

? ?print(index, "-->", items[index])


>>>

0 --> 8

1 --> 23

2 --> 45

優(yōu)雅版:


for index, item in enumerate(items):

? ?print(index, "-->", item)


>>>

0 --> 8

1 --> 23

2 --> 45

enumerate 還可以指定元素的第一個元素從幾開始,默認是0,也可以指定從1開始:


for index, item in enumerate(items, start=1):

? ?print(index, "-->", item)


>>>

1 --> 8

2 --> 23

3 --> 45

2、append 與 extend 方法有什么區(qū)別


append表示把某個數(shù)據(jù)當做新元素追加到列表的最后面,它的參數(shù)可以是任意對象


x = [1, 2, 3]

y = [4, 5]

x.append(y)

print(x)


>>>

[1, 2, 3, [4, 5]]

extend 的參數(shù)必須是一個可迭代對象,表示把該對象里面的所有元素逐個地追加到列表的后面


x = [1, 2, 3]

y = [4, 5]

x.extend(y)

print(x)


>>>

[1, 2, 3, 4, 5]


# 等價于:

for i in y:

? ?x.append(i)

3、檢查列表是否為空


普通版:


if len(items) == 0:

? ?print("空列表")


或者


if items == []:

? ?print("空列表")

優(yōu)雅版:


if not items:

? ?print("空列表")

4、如何理解切片


切片用于獲取列表中指定范的子集,語法非常簡單


items[start:end:step]

從 start 到 end-1 位置之間的元素。step 表示步長,默認為1,表示連續(xù)獲取,如果 step 為 2 就表示每隔一個元素獲取。


a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


>>> a[3:8] # 第3到第8位置之間的元素

[4, 5, 6, 7, 8]


>>> a[3:8:2] # 第3到第8位置之間的元素,每隔一個元素獲取

[4, 6, 8]


>>> a[:5] ? # 省略start表示從第0個元素開始

[1, 2, 3, 4, 5]


>>> a[3:] ?# 省略end表示到最后一個元素

[4, 5, 6, 7, 8, 9, 10]


>>> a[::] ?# 都省略相當于拷貝一個列表,這種拷貝屬于淺拷貝

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5、如何拷貝一個列表對象


第一種方法:


new_list = old_list[:]

第二種方法:


new_list = list(old_list)

第三種方法:


import copy

# 淺拷貝

new_list = copy.copy(old_list)

# 深拷貝

new_list = copy.deepcopy(old_list)

6、如何獲取列表中的最后一個元素


索引列表中的元素不僅支持正數(shù)還支持負數(shù),正數(shù)表示從列表的左邊開始索引,負數(shù)表示從列表的右邊開始索引,獲取最后一個元素有兩種方法。


>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[len(a)-1]

10

>>> a[-1]

10

7、如何對列表進行排序


列表排序有兩種方式,一種是列表自帶的方式 sort,一種是內(nèi)建函數(shù) sorted。復雜的數(shù)據(jù)類型可通過指定 key參數(shù)進行排序。由字典構(gòu)成的列表,根據(jù)字典元素中的age字段進行排序:



items = [{'name': 'Homer', 'age': 39},

? ? ? ? {'name': 'Bart', 'age': 10},

? ? ? ? {"name": 'cater', 'age': 20}]


items.sort(key=lambda item: item.get("age"))


print(items)


>>>

[{'age': 10, 'name': 'Bart'}, {'age': 20, 'name': 'cater'}, {'age': 39, 'name': 'Homer'}]

列表有 sort方法,用于對原列表進行重新排序,指定 key 參數(shù),key 是匿名函數(shù),item 是列表中的字典元素,我們根據(jù)字典中的age進行排序,默認是按升序排列,指定 reverse=True 按降序排列


items.sort(key=lambda item: item.get("age"), reverse=True)


>>>

[{'name': 'Homer', 'age': 39}, {'name': 'cater', 'age': 20}, {'name': 'Bart', 'age': 10}]

如果不希望改變原列表,而是生成一個新的有序列表對象,那么可以內(nèi)置函數(shù) sorted ,該函數(shù)返回新列表


items = [{'name': 'Homer', 'age': 39},

? ? ? ? {'name': 'Bart', 'age': 10},

? ? ? ? {"name": 'cater', 'age': 20}]


new_items = sorted(items, key=lambda item: item.get("age"))


print(items)

>>>

[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}, {'name': 'cater', 'age': 20}]


print(new_items)

>>>

[{'name': 'Bart', 'age': 10}, {'name': 'cater', 'age': 20}, {'name': 'Homer', 'age': 39}]

8、如何移除列表中的元素


刪除列表中的元素有三種方式


remove 移除某個元素,而且只能移除第一次出現(xiàn)的元素


>>> a = [0, 2, 2, 3]

>>> a.remove(2)

>>> a

[0, 2, 3]


# 如果要移除的元素不在列表中,則拋出 ValueError 異常

>>> a.remove(7)

Traceback (most recent call last):

?File "<stdin>", line 1, in <module>

ValueError: list.remove(x): x not in list·

del 根據(jù)指定的位置移除某元素


>>> a = [3, 2, 2, 1]

# 移除第一個元素

>>> del a[1]

[3, 2, 1]


# 當超出列表的下表索引時,拋出IndexError的異常

>>> del a[7]

Traceback (most recent call last):

?File "<stdin>", line 1, in <module>

IndexError: list assignment index out of range

pop 與del 類似,但是 pop 方法可以返回移除的元素


>>> a = [4, 3, 5]

>>> a.pop(1)

3

>>> a

[4, 5]


# 同樣,當超出列表的下表索引時,拋出IndexError的異常

>>> a.pop(7)

Traceback (most recent call last):

?File "<stdin>", line 1, in <module>

IndexError: pop index out of range

9、如何連接兩個列表


listone = [1, 2, 3]

listtwo = [4, 5, 6]


mergedlist = listone + listtwo


print(mergelist)

>>>

[1, 2, 3, 4, 5, 6]

列表實現(xiàn)了 + 的運算符重載,使得 + 不僅支持數(shù)值相加,還支持兩個列表相加,只要你實現(xiàn)了 對象的 __add__操作,任何對象都可以實現(xiàn) + 操作,例如:


class User(object):

? ?def __init__(self, age):

? ? ? ?self.age = age


? ?def __repr__(self):

? ? ? ?return 'User(%d)' % self.age


? ?def __add__(self, other):

? ? ? ?age = self.age + other.age

? ? ? ?return User(age)


user_a = User(10)

user_b = User(20)


c = user_a + user_b


print(c)


>>>

User(30)

10、如何隨機獲取列表中的某個元素


import random

items = [8, 23, 45, 12, 78]


>>> random.choice(items)

78

>>> random.choice(items)

45

>>> random.choice(items)

12

i

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容