专业编程基础技术教程

网站首页 > 基础教程 正文

一分钟了解python对列表元素的操作

ccvgpt 2024-08-07 18:44:59 基础教程 11 ℃


【增加-append】

>>>list = ['松','竹']
>>>list.append('梅')
>>>print(list)

['松','竹','梅']
#小括号,一次加一个

【修改】

>>>list = ['松','竹','梅']
>>>list[0] = '松树'
>>>print(list)

['松树', '竹', '梅']

【提取】

>>>list = ['松','竹','梅']
>>>print(list[0])

松

>>>list = [['松','松树'],['竹','竹子'],['梅','梅花']]
>>>print(list[0][1])

松树

#嵌套列表的提取

【删除-del】

>>>list = ['松','竹','梅']
>>>del list[0]
>>>print(list)
>>>del list[0]
>>>print(list)

['竹', '梅']
['梅']
#中括号,一次一个,重新偏移

【插入-insert】

  • 有列表 name = ['F', 'i', 'h', 'C'],在元素 'i' 和 'h' 之间插入元素 's':
name.insert(2, 's')
  • 高级用法--每次把最后一个元素挪到最前边
list1=[1,2,3,4,5]
list1.insert(0, list1.pop())
print(list1)
#结果 [5, 1, 2, 3, 4]
#某表.pop() 取出某表的最后一个,某表少一个元素

小结


一分钟了解python对列表元素的操作

over

Tags:

最近发表
标签列表