python学习-16 列表list

Posted liujinjing521

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习-16 列表list相关的知识,希望对你有一定的参考价值。

list

1.由[ ]括住,中括号内各元素由逗号隔开,各元素可以是数字,字符串,列表,布尔值等等。

例如:

li = [521,"love",["john","boy",12],True]
print(li)

ps:列表是可以嵌套的

2.取值

-索引取值:

li = [123,"love",[a,132,abc],"我爱你",True]
print(li[3])

输出结果:

我爱你

Process finished with exit code 0

-切片取值:

li = [123,"love",[a,132,abc],"我爱你",True]
print(li[1:5])

输出结果:

[love, [a, 132, abc], 我爱你, True]

Process finished with exit code 0

-循环

li = [123,"love",[a,132,abc],"我爱你",True]
for a in li :
    print(a)

输出结果:

123
love
[a, 132, abc]
我爱你
True

Process finished with exit code 0

 

2.列表元素是可以修改的

li = [123,"love",[a,132,abc],"我爱你",True]
li[0] = cao
print(li)

运行结果:

[cao, love, [a, 132, abc], 我爱你, True]

Process finished with exit code 0

也可以通过切片的方式修改:

li = [123,"love",[a,132,abc],"我爱你",True]
li[0:3] = [cao,ni,ma]
print(li)

运行结果:

[cao, ni, ma, 我爱你, True]

Process finished with exit code 0

 

2.列表元素的删除

第一种方法:

li = [123,"love",[a,132,abc],"我爱你",True]
del li[0]
print(li)

运行结果:

[love, [a, 132, abc], 我爱你, True]

Process finished with exit code 0

3.判断是否在列表里(嵌套的元素是一个整体)

li = [123,"love",[a,132,abc],"我爱你",True]
a = "abc" in li
print(a)

运行结果:

False

Process finished with exit code 0

 

以上是关于python学习-16 列表list的主要内容,如果未能解决你的问题,请参考以下文章

python学习之列表

python学习之列表

python学习之列表

python学习之列表

Python学习之列表

python学习之列表切片元祖