字符串、列表、字典、元组的基本操作

#1列表
number=[1,2,3,4,5,6]
# print(number)
#将8,9放入到列表中
#number.append(8,9) .append()只支持往列表里放一个参数
number.append(7)
# print(number)
number.extend([8,9])#.extend([, ,])需要注意extend是用列表来扩充列表,其参数是另一个列表
# print(number)
#往列表任一位置插入参数.insert(a,b)其中a表示插入位置,b表示插入的参数值
number.insert(2,10)
# print(number)
number.insert(-1,11)
print(number)
"""
从列表中获取元素
"""
#通过索引值
eggs=['鸡蛋','鸭蛋','鹅蛋','铁蛋']
print(eggs[-1])
L=len(eggs)
print(eggs[L-2])
#将列表中两个参数进行调换位置
temp=eggs[1]
eggs[1]=eggs[3]
eggs[3]=temp
print(eggs)
#便捷操作
eggs[1],eggs[3]=eggs[3],eggs[1]
print(eggs)
#从列表中抽取随机参数,调用random模块
import random
print(random.choice(eggs))
#如果列表中包含列表,该怎么提取参数呢?
breakfast=['eggs','milk',['sandwich','juice','biscuit'] ,'cigarette','cigar']
print(breakfast[2][2])
#需要注意的是在[][]之间不能加逗号,如果加逗号就是提取对应外层列表的参数
#从列表中删除元素
"""
#从列表中删除元素
remove().....指定待删的元素
pop()......取出来并删除,参数是一个索引值
del......
三种方法
"""
eggs=['鸡蛋','鸭蛋','鹅蛋','铁蛋']
eggs.remove('鹅蛋')
print(eggs)
eggs=['鸡蛋','鸭蛋','鹅蛋','铁蛋']
# eggs.pop(1)
print(eggs.pop(1))
#如果pop不带参数直接调用pop()就是默认弹出最后一个元素
print(eggs.pop())
#del的用法
eggs=['鸡蛋','鸭蛋','鹅蛋','铁蛋']
del eggs[0]
print(eggs)
"""
del eggs
print(eggs)
这里的del是直接删除变量eggs
"""
list1=[1,2,3,3,5,5,2,8,3,3]
print(list1.count(3))
#index返回某个元素第一次出现位置的索引值;
print(list1.index(3))
#reverse() 倒序
list1.reverse()
print(list1)
list1.sort()
list1.reverse()
print(list1)
"""
元祖:带上了枷锁的列表
创建列表是[ , , , , ],而元祖是( , , , , , )
"""
tuple1=(1,2,3,4,5,6,7,8,9)
print(type(tuple1))
tuple2=tuple1[:]
print(tuple2)
"""
字典{}
"""
dict1={'卢本伟':'伞兵','pdd':'死胖子','周淑怡':'全新A级车'}
print(dict1)
for each in dict1:
    print("%s是%s"%(each,dict1[each]))
    pass
empty={}
#使用内置函数dict来创建字典;
dict1=dict(A=90,B=75,C=60,D=50)
print(dict1)
#给字典的key赋value
dict1['E']=40
print(dict1)
dict1['E']=110
print(dict1)
c=dict(zip(['a','b','c'],[1,2,3]))
f=dict(a=1,b=2,c=3)
print(c==f)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值