列表

1、创建列表

 newList = []

2、向列表增加元素

newList = []
newList.append("a,b,c,d,f")
print(newList)

得到结果

['a,b,c,d,f']

3、从列表中获取元素

newList = ["a","b","c","d","f"]
print(newList[2])

得到结果

c

4、列表分片

newList = ["a","b","c","d","f"]
print (newList[1:4] )

得到结果

['b', 'c', 'd']

5、修改元素

newList = ["a","b","c","d","f"]
newList[2] = 's'
print (newList)

得到结果

['a', 'b', 's', 'd', 'f']

6、向列表中增加函数的其它方法
(1)append()向列表末尾增加一个元素。
(2)extend() 向列表末尾增加多个元素。

newList = ["a","b","c","d","f"]
newList.extend(["w","y","z"])
print (newList)

得到结果

['a', 'b', 'c', 'd', 'f', 'w', 'y', 'z']

(3)insert() 在列表中的某个位置增加一个元素,不一定非得在列表末尾。

newList = ["a","b","c","d","f"]
newList.insert(3,"s")
print (newList)

得到结果

['a', 'b', 'c', 's', 'd', 'f']

7、从列表中删除元素
(1)用 remove() 删除元素,remove() 会从列表中除你选择的元素,把它丢掉

newList = ["a","b","c","d","f"]
newList.remove("b")
print (newList)

得到结果

['a', 'c', 'd', 'f']

(2)用 del 删除,del 允许利用引从列表中除元素

newList = ["a","b","c","d","f"]
del newList[2]
print (newList)

得到结果

['a', 'b', 'd', 'f']

(3)用 pop() 删除元素,pop() 从列表中出最后一个元素交给你,并且你可以输出它

newList = ["a","b","c","d","f"]
ast = newList.pop(2)
print(ast)
print (newList)

得到结果

c
['a', 'b', 'd', 'f']

8、循环处理列表

newList = ["a","b","c","d","f"]
for newLists in newList: 
    print (newLists)

得到结果

a
b
c
d
f

9、列表排序

newList = ["a","b","c","d","f"]
newList.reverse() 
print (newList)
newList.sort()
print(newList)

得到结果

['f', 'd', 'c', 'b', 'a']
['a', 'b', 'c', 'd', 'f']
上一篇:Java语言程序设计与数据结构(基础篇)chapter7 7.15


下一篇:AI基础架构Pass Infrastructure