列表:
增删改查:
增 shijian = ['nide','yao','huyao'] a = [2012,2013,2014] b = shijian+a print(b) shijian.insert(0,'hello') print(shijian) 删 按照下标删除 shijian = ['nide','yaoguai',1,2,3,[7,8,9]] a = shijian.pop(0) print(a,shijian) 按照值删除 shijian.remove([7,8,9]) print(shijian) 改 shijian = ['nide','yaoguai',1,2,3,[7,8,9]] shijian[1]='龙族' print(shijian) 查 shijian = ['nide','yao','huyao'] for i in shijian: print(i) for i in range(len(shijian)): print(shijian[i])
排序
a = [1,12,20,8,50,6]
b = ['c','a','d','g','h']
方法一
a.sort(reverse=True)
print(a)
b.sort(reverse=True)
print(b)
方法二(比较好用)
print(sorted(a,reverse=True))
print(sorted(b,reverse=True))
字符串与列表的相互转化
字符串转变为列表
a = '1,2,3,4,5,6'
print(a.split(','))
列表转化为字符串
b = a.split(',')
c = ','.join(b)
print(c)
补充
demo1 = '123'
print(list(demo1))
例:demo1=[1,2,3,'nide',[7,8,9],'yaoguai',10]
切片
print(demo1[3:6])
倒序
print(nide[::-1])
取里层
print(nide[4][1])
取随机数
随机从列表中取一个数
a = ['c','d','a','w','d']
b = random.choice(a)
print(b)
从范围中随机取值
a = random.randrange(1,10)
print(a)
用python写一个简单计算机:
demo1 = input('请输入第一个数:')
print("""
1 +
2 -
3 *
4 /
""")
demo2 = input('请输入运算符号:')
demo3 = input('请输入第二个数:')
print(eval(demo1+demo2+demo3))