首页 > 编程语言 > 详细

python3--列表

时间:2020-06-15 00:41:08      阅读:53      评论:0      收藏:0      [点我收藏+]

alist=[10,3.14,‘hello‘,[200,300]]

1、切片操作:print(alist[:1])   结果:[10]   切片出来的类型和原数据类型保持一致

2、列表常用操作:

#1查询:获取元素---最快是下标获取

alist=[10,3.14,hello,[200,300]]
print(alist[0])
结果:
10

获取下标:

alist=[10,3.14,hello,[200,300]]
print(alist.index(10))
结果:
0

#2修改

alist[0]=50

print(alist)   结果:[50,3.14,‘hello‘,[200,300]]

#3增加元素

3-1:列表名:append(需要增加的元素值)---从尾部增加

alist.append(50)

print(alist) 结果:[10,3.14,‘hello‘,[200,300],50]

3-2:插入值   列表名.insert(需要的位置下标,插入的值)

alist.insert(0,50)

print(alist)  结果:[50,10,3.14,‘hello‘,[200,300]]

#4删除

1、del---使用下标删除

alist=[10,3.14,hello,[200,300]]
del alist[0],alist[1]
print(alist)
结果:
[3.14, [200, 300]]
alist=[10,3.14,hello,[200,300]]
del alist[1:1+2] #利用切片删除
print(alist)
结果:
[10, [200, 300]]

2、pop(下标)----有返回值

alist=[10,3.14,hello,[200,300]]
print(alist.pop(0))
print(alist)

结果:

10

[3.14, ‘hello‘, [200, 300]]

3、remove(元素值) --每次只能删除第一个出现的值,

alist=[10,3.14,hello,[200,300]]
alist.remove(3.14)
print(alist)
结果:
[10, ‘hello‘, [200, 300]]

如果要删除多个重复元素,用while N in alist:alist.remove

alist=[10,3.14,hello,[200,300]]
while 10 in alist:
    alist.remove(10)
print(alist)
结果:
[3.14, ‘hello‘, [200, 300]]

#5合并列表

法1:零时合并,不影响原列表

alist=[10,3.14,hello,[200,300]]
print(alist+[1,2])
print(alist)
结果:
[10, 3.14, hello, [200, 300], 1, 2]
[10, 3.14, hello, [200, 300]]

法2:扩展列表,会改变原列表

alist=[10,3.14,hello,[200,300]]
alist.extend([1,2])
print(alist)
结果:
[10, 3.14, hello, [200, 300], 1, 2]

 

python3--列表

原文:https://www.cnblogs.com/guang2508/p/13127619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!