共計(jì) 569 個字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中,列表(List)是一個有序的元素集合,可以使用 insert() 函數(shù)在指定位置插入一個元素。
insert() 函數(shù)的語法如下:
list.insert(index, element)
其中,index 表示要插入元素的位置,element 表示要插入的元素。
下面是一個示例:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits)
運(yùn)行上述代碼,會輸出:
["apple", "orange", "banana", "cherry"]
在這個例子中,我們在位置 index= 1 處插入了元素 "orange",原本的 "banana" 被向后移動了一個位置。
需要注意的是,如果插入的位置超出了列表的范圍(index 大于列表長度),元素將被插入到列表的末尾。
另外,如果要插入多個元素,可以使用 extend() 函數(shù)。例如:
fruits = ["apple", "banana", "cherry"]
fruits.extend(["orange", "grape"])
print(fruits)
輸出:
["apple", "banana", "cherry", "orange", "grape"]
在這個例子中,我們通過 extend() 函數(shù)一次插入了兩個元素。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完