IT@程序员猿媛

class2-列表

2019-05-04  本文已影响15人  凌航

列表和c中的数组很像,但是list可以存储不同类型的数据

创建

name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))

['鲁班', 'xiaoming', 1024]
<class 'list'>

访问

用索引进行访问

print(name_list[0])
for name in name_list:
    print(name)

鲁班
鲁班
xiaoming
1024

更新

添加
str = 'lingyu'
name_list.append(str)
print(name_list)
list1 = []
for i in range(10):
    list1.append(i)
print(list1)

['鲁班', 'xiaoming', 1024, 'lingyu']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a = [0,1,2]
a.insert(1,'j')
print(a)

[0, 'j', 1, 2]

a = [1,2]
b = [3,4]
a.append(b)
print(a)
a.extend(b)
print(a)

[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]

修改
name_list[1] = '小明'
print(name_list)

['鲁班', '小明', 1024]

删除
name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
del name_list[0]
print(name_list)
del name_list
print(name_list)

['鲁班', 'xiaoming', 1024]
<class 'list'>
['xiaoming', 1024]
name 'name_list' is not defined

name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
name_list.pop()
print(name_list)

['鲁班', 'xiaoming', 1024]
<class 'list'>
['鲁班', 'xiaoming']

name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
name_list.remove('xiaoming')
print(name_list) 

['鲁班', 'xiaoming', 1024]
<class 'list'>
['鲁班', 1024]

查找

name_list = ['鲁班','xiaoming',1024]
print(name_list)
print(type(name_list))
findName = '小明'
if findName in name_list:
    print('小明在列表中')
else:
    print('不在')

['鲁班', 'xiaoming', 1024]
<class 'list'>
不在

排序

排序有sort和sorted两种方法,它们有一下两种区别:

from random import randint

num_list = []
for i in range(10):
    num_list.append((randint(1,20)))
print(num_list)
num_list.sort()
print(num_list)
num_list.sort(reverse=True)
print(num_list)

new_list = sorted(num_list)
print(num_list)
print(new_list)

[6, 16, 4, 15, 13, 19, 20, 16, 7, 5]
[4, 5, 6, 7, 13, 15, 16, 16, 19, 20]
[20, 19, 16, 16, 15, 13, 7, 6, 5, 4]
[20, 19, 16, 16, 15, 13, 7, 6, 5, 4]
[4, 5, 6, 7, 13, 15, 16, 16, 19, 20]

嵌套

列表的成员可以是列表,相当于多维数组,这里以二维列表举例

school_name = [['qinghua','beida'],['nankai','tianda'],['dongqin','yanda']]
print(school_name)
print(school_name[0][1])

[['qinghua', 'beida'], ['nankai', 'tianda'], ['dongqin', 'yanda']]
beida

列表推导式,用于轻量级的循环创建

from random import randint
l = [randint(-10,10) for _ in range(10)]
print(l)
res2 = [x for x in l if x>=0]
print('使用列表解析筛选',res2)

[10, -1, -8, -4, -2, 7, 2, -8, -3, 7]
使用列表解析筛选 [10, 7, 2, 7]

上一篇下一篇

猜你喜欢

热点阅读