当前位置:首页 » 《资源分享》 » 正文

【python基础学习】五、列表、元组、字典_(∪.∪ )...zzz的博客

7 人参与  2021年10月16日 16:43  分类 : 《资源分享》  评论

点击全文阅读


这里写自定义目录标题

  • 列表 list
    • 常用操作
    • 循环遍历
  • 元组 Tuple
    • 常用操作:取值取索引、计数
    • 元组的应用场景
    • 元组、列表 的转换
  • 字典 dictionary
    • 字典 常用操作:增删改查
    • 统计、合并
    • 字典的遍历
    • 字典和列表

列表 list

  • 其他语言中——数组
  • 存储一串信息
  • [x,y,z]
  • 列表的索引从0开始
  • 不可超出所应范围,会报错

常用操作

在这里插入图片描述
在这里插入图片描述




list01 = ["1","2","3","3","2","6"]



# del 是从内存中删除

del list01[1]

print(list01)

# 统计长度
print(len(list01))

# 统计出现几次
count = list01.count("3")
print(count)

# remove 列表中第一个出现的
list01.remove("3")
print(list01)


# 排序
 # 升序
list01.sort()
print(list01)

 # 降序
list01.sort(reverse=1)
print(list01)

# 反转
list01.reverse()
print(list01)

循环遍历

list02 =["2","3","4"]
for i in list02:
     print(i)
2
3
4

元组 Tuple

  • 与list相似,但元素不能修改
  • (x,y,z)
  • 索引从0开始
  • 创建空元组 tuple=()
  • 通常存储不同类型的数据
tuple =("woai",1,0.99)

print(type(tuple))
# python解释器,直接认为是数据类型
# <class 'int'>
t=(2)
print(type(t))

# 要定义一个只包含一个元素的元组
# 要跟上逗号
# <class 'tuple'>

t1=(2,)
print(type(t1))

常用操作:取值取索引、计数

t = ("where are you now",1,2,2)

# 取值
print(t[0])  # where are you now

# 取索引
print(t.index("where are you now")) # 0

# 统计计数
print(t.count(2))   # 2


# 统计元组中元素的个数
print(len(t))   # 4

元组的应用场景

  • 元组可作为函数的参数、返回值
  • 格式字符串,本质上就是元组
  • 让列表不可以被修改,保护数据安全
tuple1 = ("aaa",21,188)
print("%s 年龄是%d的身高是%d" % tuple1)

tuple1str = "%s 年龄是 %d的身高是%d"%tuple1
print(tuple1str)

元组、列表 的转换

# <class 'tuple'>
t = (1,23,34)
print(type(t))


# <class 'list'>
list(t)
print(type(list(t)))

字典 dictionary

  • 列表是有序的 对象集合
  • 字典是无序的 对象集合
  • {x,y,z}
  • 键值对 键:值
  • 在这里插入图片描述
dict = {"name":"gggg",
        "age":20,
        "height":190
       }

print(dict)

# {'name': 'gggg', 'age': 20, 'height': 190}
# 打印顺序可能和字典的顺序不一致

字典 常用操作:增删改查

dict = {"name":"gggg",
        "age":20,
        "height":190
       }

print(dict)

print("取值:",end="")
print(dict["name"])

print("增加、修改:",end="")
dict["weight"]=200  # key不存在,新增键值对
dict["name"]="ggg"  # key存在,修改为小小明
print(dict)

print("删除:",end="")
dict.pop("name")
print(dict)


{'name': 'gggg', 'age': 20, 'height': 190}
取值:gggg
增加、修改:{'name': 'ggg', 'age': 20, 'height': 190, 'weight': 200}
删除:{'age': 20, 'height': 190, 'weight': 200}

统计、合并



dict = {"name":"gggg",
        "age":20,
        "height":190
       }
# 键值对的数量

print("键值对的数量")
print(len(dict))

# 合并字典
# {'name': 'gggg', 'age': 20, 'height': 190, 'perfer': 111}
temp_dict = {
    "perfer":111
}
dict.update(temp_dict)
print(dict)

# 清空字典
dict.clear()
print(dict)

字典的遍历

for i in dict:
    print("%s-%s"%(i,dict[i]))

字典和列表

字典嵌在 列表中


点击全文阅读


本文链接:http://zhangshiyu.com/post/29947.html

字典  列表  遍历  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1