python学习(五):数据类型list列表,tuple元组,dict字典的使用

#list列表操作
def testList():
    #定义一个空列表
    strList=[]
    #新增
    strList.append("a")
    strList.append("b")
    strList.append("1")
    strList.append("2")
    #循环
    for item in strList:
        print(item)
    #或这么写循环
    length=len(strList)
    index=0
    while index<length:
        print(strList[index])
        index+=1
    #删除数组第二个元素
    del strList[1]
    for item in strList:
        print(item)

#tuple元组元素不可以修改或删除
def testTuple():
    # 定义一个tuple
    my_tuple = (1, 2, 3, 4, 5)

    # 使用for循环遍历tuple中的元素
    for item in my_tuple:
        print(item)

    #元组和列表可以互转
    my_list = list(my_tuple)
    my_list[3] = 9
    my_tuple = tuple(my_list)
    #第4个元素被改成了9
    for item in my_tuple:
        print(item)


#dict字典操作
def testDict():
    # 创建字典
    my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

    # 访问字典元素
    print(my_dict['name'])  # 输出: Alice
    print(my_dict.get('age'))  # 输出: 25

    # 添加或修改字典元素
    my_dict['age'] = 26  # 修改
    my_dict['job'] = 'Engineer'  # 添加

    # 删除字典元素
    del my_dict['city']  # 删除键为'city'的条目

    # 遍历字典
    for key, value in my_dict.items():
        print(key, value)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值