列表相当于一个容器,可以把一系列相关的值放在这个容器中进行存储

一.列表介绍:

1.定义列表:使用左右两个中括号的形式。

fruits = ['apple','orange','pears']
#列表中也可以存放不同的数据类型
test_list = ['abc',1]

2.取列表中的值:列表也可以像字符串的下标操作一样。

fruits = ['apple','orange','pears']
fruits_1 = fruits[0]
fruits_2 = fruits[2]
print(fruits_1)
print(fruits_2)

打印结果:
apple
pears

3.列表的遍历:分为while和for循环遍历,但一般采取for循环。

for循环版本:
fruits = ['apple','orange','pears']
#可以仿照该格式
for fruit in fruits:
    print(fruit)
    
打印结果:
apple
orange
pears
while循环版本:
fruits = ['apple','orange','pears']
index = 0
while index < len(fruits):
    print(fruits[index])
    index += 1

4.列表嵌套:列表中可以存储任何数据类型,当然也包括列表自身类型。

fruits = ['apple','orange',['small_pears','big_pears']]
for fruit in fruits:
    print(fruit)

打印结果:
apple
orange
['small_pears', 'big_pears']

5.列表相加:相当于把后面一个列表的数据追加到第一个列表后面。

a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)

打印结果:
[1, 2, 3, 4, 5, 6]

6.列表的切片操作:与字符串的切片操作一样。( )

(1)开始位置:包括开始位置。
          (2)结束位置:会取到借书位置前一个元素
          (3)步长:默认为1,如果步长为负数,则从右到左,反之从左到右
          (4)切片可以赋值
          (5)逆序:list[-1::-1]

二.列表常用方法

1.append:在列表末尾添加元素

friuts = ['orange']
friuts.append('apple')
print(friuts)
打印结果:
['orange', 'apple']

2.account:统计某个元素在列表中出现的次数

index = ['I','love','python','python','is','easy']
print(index.count('python'))
打印结果:
2

3.extend:将一个列表中的元素追加到另外一个列表中(注:该方法
与列表加运算的主要区别在于 加方法不改变原来的列表 而extend方法
会改变原来的列表)

a = [1,3,5]
b = [2,4,6]
a.extend(b)
print(a)
打印结果:
[1, 3, 5, 2, 4, 6]

4.index:找出列表中第一个某个值的第一根匹配项的索引位置,如果没有找到,则抛出一个异常

knight = ['hello','world']
print(knight.index('hello'))
打印结果:
0

5.insert:将某个值插入到列表中的某个位置

chars = ['hello','world']
chars.insert(1,'nihao')
print(chars)
打印结果:
['hello', 'nihao', 'world']

6.pop:移除列表中最后一个元素,并且返回该元素的值:

x = [1,2,3]
temp = x.pop()
print(temp)
打印结果:
3

7.remove:移除列表中第一个匹配的元素,不会返回这个被移除的元素的值。如果被移除的这个值不存在在列表
中,则会抛出一个异常

num = [1,2,3]
num.remove(2)
print(num)
打印结果:
[1, 3]

8.reverse:将列表中的元素反向存储,会改变原来列表中的值

x = [1,3,5,7,9]
x.reverse()
print(x)
打印结果:
[9, 7, 5, 3, 1]

9.sort:将列表中的元素进行排序,会更改原来列表中的位置
sorted: 不会更改原来列表的位置,并且会返回一个排序后的值

y = [4,2,1,5,3]
y.sort()
print(y)
打印结果:
[1, 2, 3, 4, 5]

y = [4,2,1,5,3]
new_y = sorted(y)
print(new_y)
print(y)
打印结果:
[1, 2, 3, 4, 5]
[4, 2, 1, 5, 3]

10.del:根据下标删除元素

test = [5,7,13]
del test[2]
print(test)
打印结果:
[5, 7]

11.使用in判断列表中是否有某个元素

test1 = [7,8,9]
if 7 in test1:
    print(True)
else:
    print(False)
 打印结果:
 True

12.list:函数,将其他数据类型转换成列表

test2 = 'hello,world'
new_test2 = list(test2)
print(new_test2)
打印结果:
['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd']