遍历链表
animals = ['pig','dog','cat','panda','tiger']
for animal in animals:
print(animal)
pig
dog
cat
panda
tiger
列表解析
name_of_list = [f(value) for (为value供值)]
squares = [values**2 for values in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print( [i for i in range(0,5)])#range 函数左闭右开
[0, 1, 2, 3, 4]
切片
print(animals[:3])#从头到ind,Python是左闭右开
['pig', 'dog', 'cat']
print(animals[2:])# 从ind到末尾
['cat', 'panda', 'tiger']
print(animals[:])#输出list全部值
['pig', 'dog', 'cat', 'panda', 'tiger']
print(animals[-3:])#输出list倒数三个值
['cat', 'panda', 'tiger']
复制
w_animals = animals[:]
h_animals = animals
print(w_animals) #这一种是w_animals另外开辟一个地址空间,然后将animals里面的值赋值
print(h_animals) #这一种是直接将animals指向的地址空间赋值给h_animals
['pig', 'dog', 'cat', 'panda', 'tiger']
['pig', 'dog', 'cat', 'panda', 'tiger']
h_animals.append('snake')
print(animals)#可以发现animals和h_animals的内容都变了
['pig', 'dog', 'cat', 'panda', 'tiger', 'snake', 'snake']