路飞学城-Python 开发集训-小总结

列表的介绍

列表由一系列按特定顺序排列的元素组成,你可以创建包含字母表中所有字母、数字0-9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。鉴于列表通常包含多个元素,给列表指定一个表示复数的名称(如letters、digits或names)是个不错的注意。

在python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。下面是一个简单列表示例:

列表示例

1.首先定义一个列表

names = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]

2.通过下标访问列表中的元素,下标从0开始计数。

print(names[0])#取出列表里面的第一个下标,并输出结果。
>>>"One"
print(names[-1])#取出列表里的最后一个下标,并输出结果。
>>>"Ten"

3.切片:取多个元素

print(names[1:4])#取下标0到4之间的数字,包括0不包括4
>>>["One","Two","Three"]
print(names[1:-1])#取下标0到-1之间的数字,包括1不包括-1
>>>["Two","Three","Four","Five","Six","Seven","Eight","Nine"]
print(names[0:5])
>>>["One","Two","Three","Four","Five"]
print(names[:5])#如果取下标是从头开始的话,我们0可以省略,跟上面的代码效果是一样的。
>>>["One","Two","Three","Four","Five"]
print(names[5:])#如果从最后一个倒着取,那么必须不能写-1,只能这么写。
>>>["Six","Seven","Eight","Nine","Ten"]
print(names[1:-1])#如果这样写,那就是从下标第一个值取到最后一个值的前1位,也就是不包含-1
>>>["Two","Three","Four","Five","Six","Seven","Eight","Nine"]
print(names[0:-1:2])
>>>['One', 'Three', 'Five', 'seven', 'nine']
print(names[::2])#后面的2代表,每隔一个元素,取一个值。跟上面效果是一样的。
>>>['One', 'Three', 'Five', 'seven', 'nine']

4.追加

names.append("新数据")#在列表的最后增加一个新的值,
print("names")
>>>["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","新数据"]

5.插入

names.insert(1,"占用位置")#1是占用的下标值,"" 是占用的内容
print(names)
>>>["One","占用位置","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]

6.修改/更换

names[5]="把Six替换"#[]是更换的下标,"" 是更换的新内容
print[names]
>>>["One","Two","Three","Four","Five","把Six替换","Seven","Eight","Nine","Ten"]

7.删除

del names[5]#删除列表下标指定元素
print(names)
>>>["One","Two","Three","Four","Five","Seven","Eight","Nine","Ten"]
names.remove("Four")#删除列表指定数字元素
print(names)
>>>["One","Two","Three","Five","Six","Seven","Eight","Nine","Ten"]
names.pop()#删除列表最后一个值 "Ten"
print(names)
>>>["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]

人已赞赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧