列表更多的方法
- index():返回指定数据所在位置的下标 (注意:如果查找的数据不存在则报错。)。
- count():统计指定数据在当前列表中出现的次数。
- len():访问列表?度,即列表中数据的个数。
- in:判断指定数据在某个列表序列,如果在返回True,否则返回False
- not in:判断指定数据不在某个列表序列,如果不在返回True,否则返回False
- append():列表结尾追加数据。
- extend():列表结尾追加数据,如果数据是?个序列,则将这个序列的数据逐?添加到列表。
- insert():指定位置新增数据。
- pop():删除指定下标的数据(默认为最后?个),并返回该数据。
- remove():移除列表中某个数据的第?个匹配项。
- clear():清空列表
- 逆置:reverse()
- 排序:sort()
- copy()
def generateRandomList(a, b, n, random_state):
from random import randint, seed
seed(random_state)
ls = []
for i in range(n):
ls.append(randint(a, b))
return ls
ls = generateRandomList(0, 100, 10, 666)
print(ls)
print(ls.index(55))
print(ls.index(70))
print(ls.index(70, 7, 9))
print(ls.count(70))
print(ls.count(58))
print(ls.count(666))
print(len(ls))
for i in range(len(ls)):
print(ls[i])
for x in ls:
print(x)
def my_index(ls, val):
for i in range(len(ls)):
if ls[i] == val:
return i
return -1
print("myindex = ", my_index(ls, 70))
print("myindex = ", my_index(ls, 101))
print(69 in ls)
print(70 in ls)
print(70 not in ls)
print(69 not in ls)
hero_ls = []
hero_ls.append("鲁班七号")
hero_ls.append("妲己")
hero_ls.append(123)
print(hero_ls)
hero_ls.insert(1, "校领导")
hero_ls.insert(1, "校领导夫人")
print(hero_ls)
hero_ls.extend("BBQ")
print(hero_ls)
hero_ls.extend(['瑶', '暃'])
hero_ls.extend(['123'])
print(hero_ls)
print(hero_ls.pop())
print(hero_ls.pop())
print(hero_ls.pop(1))
print(hero_ls)
hero_ls.remove('妲己')
print(hero_ls)
hero_ls.clear()
print(hero_ls)
lss = [1, 2, 3, 4, 5]
lss.reverse()
print(lss)
print(ls)
ls.sort()
print(ls)
ls.sort(reverse=True)
print(ls)
nls = lss.copy()
print(nls)
print(nls)
列表的嵌套
列表中还有列表, 可以表示数学中的矩阵
name_list = [['?明', '?红', '?绿'],
['Tom', 'Lily', 'Rose'],
['张三', '李四', '王五']]
print(name_list[1])
print(name_list[1][0])
练习
def generate(n):
total_ls = []
for i in range(n):
ls = []
for j in range(i+1):
ls.append('* ')
total_ls.append(ls)
return total_ls
print(generate(6))
for row in generate(6):
for v in row:
print(v, end='')
print()
def send1(money, count):
money*=100
m = money//count
l = money%count
bag = []
for i in range(count-1):
bag.append(m/100)
if l == 0:
bag.append(m/100)
else:
bag.append((m+l)/100)
return bag
print(send1(100, 3))
def send2(money, count):
money *= 100
from random import randint
bag = []
for i in range(count - 1):
m = money // count
cur = 2*randint(0, m-1)
money -= cur
bag.append(cur/100)
bag.append(money/100)
return bag
print(send2(100, 3))
print(sum(send2(100, 3)))
|