Python基础之列表、元组、字典、集合的使用

本文详细介绍了Python中列表和字典的基本操作,包括列表的切片、追加与删除,列表复制的区别,以及如何利用for循环遍历列表。同时,还介绍了字典的定义、查询、更新和删除等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、列表

1、列表定义

names=["Jhon","Lucy","Michel","Tom","Wiliam"]

列表切片:

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",'GuYun']
print(names)
print(names[0])
print(names[1:3]) #不能取到索引为3的列表元素
print(names[-1])#取列表的倒数第一位的值
print(names[-2:]) #取倒数两个值
print(names[0:3])
print(names[:3]) #与print(names[0:3]) 等价

print(names.index("GuYun"))  # 打印输出索引值
print(names[names.index("GuYun")])
print(names.count("LiYun"))  #打印输出列表中"LiYun"的个数

 结果:

['HeXin', 'ZhangLiang', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun']
HeXin
['ZhangLiang', ['caijie', 'LiSi']]
LiYun
['GuYun', 'LiYun']
['HeXin', 'ZhangLiang', ['caijie', 'LiSi']]
['HeXin', 'ZhangLiang', ['caijie', 'LiSi']]
5
GuYun
2

 2、列表元素的追加与删除

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",'GuYun',"LiYun"]
print(names)
#列表追加:
names.append("李斯") #默认插入到列尾
names.insert(1,"唐宇") #指定位置插入
names[2]="肖静" #指定位置插入
print("-----after append-----\n",names) #列表删除: names.remove("LiYun") del names[1] #删除列表中索引为1的值 names.pop()#默认删除最后一个值 names.pop(0)#删除第一个值 print("-----after delete-----\n",names)

 运行结果:

['HeXin', 'ZhangLiang', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun']
-----after append-----
 ['HeXin', '唐宇', '肖静', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun', '李斯']
-----after delete-----
 ['肖静', ['caijie', 'LiSi'], 'TianJun', 'GuYun', 'LiYun']

删除整个列表:del names 

反转列表值的位置:name.reverse()

排序:names.sort()

3、列表复制

语句:import copy

列表扩展:

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",'GuYun',"LiYun"]
print(names)

names2=[1,2,3,4]
names.extend(names2) #将names2的值添加到names中
print(names,names2)

 运行结果:

['HeXin', 'ZhangLiang', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun']
['HeXin', 'ZhangLiang', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun', 1, 2, 3, 4] [1, 2, 3, 4]

 列表复制与变量复制略有不同:

import copy
#变量的复制:
name1="LiHai"
name2=name1
name1="TianJun"
print("-----name1>>",name1)
print("-----name2>>",name2)

#列表的复制:
names=['1','2','3']
names2=names.copy() #浅copy
names[0] = 55
print("-----names>>",names)
print("-----names2>>",names2)

names3=[1,2,[5,7],3]
print("-----修改前的names3>>",names3)
names4=copy.copy(names3) #浅copy
names5=copy.deepcopy(names3) #深copy
names3[2][0]=66
names3[0]=88
print("-----names3>>",names3)
print("-----names4>>",names4)
print("-----names5>>",names5)

 结果:

-----name1>> TianJun
-----name2>> LiHai
-----names>> [55, '2', '3']
-----names2>> ['1', '2', '3']
-----修改前的names3>> [1, 2, [5, 7], 3]
-----names3>> [88, 2, [66, 7], 3]
-----names4>> [1, 2, [66, 7], 3]
-----names5>> [1, 2, [5, 7], 3]

 变量name2被赋值之后不会随name1的改变而改变,列表mames5在深copy的条件下,其结果与变量的复制效果一样,并没有随names3的改变而改变;而列表names4通过浅copy后,其最外层不会随names3的改变而改变,但内层会随names3的改变而改变。

4、利用for循环打印列表names

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",'GuYun',"LiYun"]
for i in names:
    print(i)

 结果:

HeXin
ZhangLiang
['caijie', 'LiSi']
LiYun
TianJun
GuYun
LiYun

 5、不用for循环打印列表

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",'GuYun',"LiYun"]
print(names[0:-1:2]) #打印列表中索引值为0到-1的值,步长为2
print(names[::1]) #打印列表中所有值

 结果:

['HeXin', ['caijie', 'LiSi'], 'TianJun']
['HeXin', 'ZhangLiang', ['caijie', 'LiSi'], 'LiYun', 'TianJun', 'GuYun', 'LiYun']

 注意:列表打印属于“顾头不顾尾”,如print(names[0:2]) ,结果只能输出列表的前两个值。

利用列表书写购物车程序:

(1)启动程序后,让用户输入工资,然后打印商品列表;

(2)用户输入相应的商品编号购买商品

(3)用户输入商品编号后,系统检测余额是否足够,足够则直接扣款,不够则提示

(4)可随时退出购物,并打印已购商品和余额

shopping_list=[]
product_list=[
    ['iphone',5800],
    ['mac pro',9800],
    ['bike',800],
    ['watch',10600],
    ['coffee',31]
]

salary=input('input your salary:')
if salary.isdigit():
    salary=int(salary)
    while True:
        for index, item in enumerate(product_list):#enumerate:读取列表的索引
            #print(product_list.index(item),item) 等价于上一句话
            print(index,item)
        user_choice=input('选择要买什么?')
        if user_choice.isdigit():#如果输入的是数字
            user_choice=int(user_choice)#将字符窜转换为整型
            if user_choice <len(product_list) and  user_choice>=0:#如果用户输入的数字在user_choice列表的长度范围之内
                p_item=product_list[user_choice]#product_list列表中商品价格赋值给p_item
                if p_item[1] <= salary:
                   shopping_list.append(p_item)
                   salary-=p_item[1]
                   print('Added %s into shopping cart,your current banlance is \033[31;1m%s\033[0m'%(p_item,salary))
                else:
                   print('\033[41;1m你的余额只剩[%s]啦\033[0m'% salary)
            else:
                print('product code[%s] is not exist'% user_choice)
        elif user_choice=='q':
            print('....shopping list....')
            for p in shopping_list:
                print(p)
            print('your current balance:',salary)
            exit()
        else:
            print('Invalid option')

 二、元组

元组一旦创建不能修改,所以又叫只读列表。

元组只有两个方法:count和index

元组定义:names=('Jim','Lucy')

三、字典

字典是一种Key-value的数据类型,是无序的。

1、字典相关操作

#字典定义 :
info={'stu001':'Lily',
      'stu002':'Jack',
      'stu003':'John',
}
print(info)
print(info['stu002']) #打印输出stu002的值
info["stu002"]="张三" #修改值
info["stu004"]="HeQian" #新增
#del info #删除字典info
del info["stu001"]  #删除指定值
print("操作后的字典>>>",info)

b={
    'stu001':"yanlin",
    1:3,
    2:5}
info.update(b)#更新字典
print("更新后的字典>>>",info)

c=info.fromkeys([6,7,8],"test")#初始化新字典,并给每个key赋值test
print("初始化后的字典>>>",c)
print(info.items())#字典转成列表

c=dict.fromkeys([6,7,8],[1,{"name":"Micle"},234])#初始化新字典,三个key将共享一个值
print(c)
c[7][1]['name']="Cherry"#修改字典值
print(c)

print("--------字典循环 ------")
for i in info:
    print(i,info[i])#推介使用此方法循环
print("---------")

for k,v in info.items():
    print(k,v)

 结果:

{'stu003': 'John', 'stu002': 'Jack', 'stu001': 'Lily'}
Jack
操作后的字典>>> {'stu003': 'John', 'stu002': '张三', 'stu004': 'HeQian'}
更新后的字典>>> {1: 3, 'stu002': '张三', 'stu001': 'yanlin', 'stu004': 'HeQian', 'stu003': 'John', 2: 5}
初始化后的字典>>> {8: 'test', 6: 'test', 7: 'test'}
dict_items([(1, 3), ('stu002', '张三'), ('stu001', 'yanlin'), ('stu004', 'HeQian'), ('stu003', 'John'), (2, 5)])
{8: [1, {'name': 'Micle'}, 234], 6: [1, {'name': 'Micle'}, 234], 7: [1, {'name': 'Micle'}, 234]}
{8: [1, {'name': 'Cherry'}, 234], 6: [1, {'name': 'Cherry'}, 234], 7: [1, {'name': 'Cherry'}, 234]}
--------字典循环 ------
1 3
stu002 张三
stu001 yanlin
stu004 HeQian
stu003 John
2 5
---------
1 3
stu002 张三
stu001 yanlin
stu004 HeQian
stu003 John
2 5

 2、字典嵌套

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"#修改内容
print(av_catalog["大陆"]["1024"]) #打印输出被修改的内容
av_catalog.setdefault("taiwan",{"www.baidu.com":[1,2]}) #新增字典元素
print(av_catalog)
av_catalog.setdefault("大陆",{"www.baidu.com":[1,2]})
print(av_catalog)

 结果:

['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']
{'日韩': {'tokyo-hot': ['质量怎样不清楚,个人已经不喜欢日韩范了', '听说是收费的']}, '大陆': {'1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']}, 'taiwan': {'www.baidu.com': [1, 2]}, '欧美': {'www.youporn.com': ['很多免费的,世界最大的', '质量一般'], 'letmedothistoyou.com': ['多是自拍,高质量图片很多', '资源不多,更新慢'], 'x-art.com': ['质量很高,真的很高', '全部收费,屌比请绕过'], 'www.pornhub.com': ['很多免费的,也很大', '质量比yourporn高点']}}
{'日韩': {'tokyo-hot': ['质量怎样不清楚,个人已经不喜欢日韩范了', '听说是收费的']}, '大陆': {'1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']}, 'taiwan': {'www.baidu.com': [1, 2]}, '欧美': {'www.youporn.com': ['很多免费的,世界最大的', '质量一般'], 'letmedothistoyou.com': ['多是自拍,高质量图片很多', '资源不多,更新慢'], 'x-art.com': ['质量很高,真的很高', '全部收费,屌比请绕过'], 'www.pornhub.com': ['很多免费的,也很大', '质量比yourporn高点']}}

 3、三级菜单的实现

data = {
    "北京":{
        "朝阳":{
            "yi":['炸鸡','汉堡','03'],
            "er":['可乐','雪碧']
        },
        "昌平":{
            "san":['06','益达','023'],
            "si":['米饭','玉米']
        },
    },
    "四川":{
        "成都": {
            "双流": ['肥肠粉', '麻辣烫'],
            "新都": ['烧烤', '卤鸡脚']
        },
        "绵阳": {
            "wu": ['啤酒', '香槟', '鸭脖'],
            "liu": ['柠檬', '橘子']
        },
    },
    "安徽":{
        "合肥": {
            "qi": ['011', '042', '063'],
            "ba": ['104', '105']
        },
        "黄山": {
            "jiu": ['066', '07', '033'],
            "shi": ['304', '025']
        }
    }
}
ch1=False
while  not ch1:
    for i in data:
        print(i)
    choice1=input('>>>:')
    if choice1 in data:
        while not ch1:
            for i2 in data[choice1]:
                print("\t",i2)
            choice2 = input('>>>:')
            if choice2 in data[choice1]:
                while not ch1:
                    for i3 in data[choice1][choice2]:
                        print("\t\t",i3)
                    choice3 = input('>>>:')
                    if choice3 in data[choice1][choice2]:
                            for i4 in data[choice1][choice2][choice3]:
                                print("\t\t\t", i4)
                            choice4=input('已经是最后一层,按b返回到上一级>>>:')
                            if choice4=="b":
                                pass
                            elif choice4=="q":
                                ch1=True
                    if choice3 == "b":
                        break
                    elif choice3 == "q":
                        ch1 = True
            if choice2 == "b":
                break
            elif choice2 == "q":
                ch1 = True

 四、集合

集合是一个无序的、不重复的数据组合。

list1=[1,4,5,6,3,5,3,6] #定义一个列表
list1=set(list1) #变成集合,去重
list2=set([3,5,33,67,8,6])
list3=set([3,5,6])
list4=set([4,2])
print(list1,type(list1))

print(list1.intersection(list2))#取两个集合的交集
print(list1.union(list2))#取并集
print(list1.difference(list2))#取差集,即在list1中有的,在list2中没有的
print(list1.issubset(list2))#子集
print(list1.issuperset(list2))
print(list3.issubset(list1))#list3是list1的子集
print(list1.symmetric_difference(list2))#对称差集,即取双方互相没有的值
print("----------")

print(list2.isdisjoint(list4))#判断是否有交集
print(list1 & list2)#交集
print(list2 | list1)#并集
print(list1 - list2)#差集
print(list1 ^ list2)#对称差集

list4.add(78)#添加一个值
list4.update([00,22])#添加多个值
list4.remove(2)#删除
print(list4)
print(list1.pop())#删除任意一个值,并返回删除的值
print(list2.discard("34"))#删除指定值,若不存在该值,系统不会报错,有别于remove

 运行结果:

{1, 3, 4, 5, 6} <class 'set'>
{3, 5, 6}
{1, 33, 3, 4, 5, 6, 67, 8}
{1, 4}
False
False
True
{33, 1, 67, 4, 8}
----------
True
{3, 5, 6}
{33, 1, 67, 3, 5, 6, 4, 8}
{1, 4}
{33, 1, 67, 4, 8}
{0, 4, 78, 22}
1
None

 

### Python 数据结构概述 #### 列表 (List) 列表是一种有序的数据容器,允许存储重复项并支持索引访问。可以动态调整大小,在创建之后能够方便地添加或删除元素。 - **定义方式**: 使用方括号 `[]` 或者内置函数 `list()` ```python my_list = [1, 2, 'three', True] empty_list = list() ``` - **特性** - 支持切片操作来获取子序列[^1]。 - 提供多种方法用于修改内容,比如 `.append()` 和 `.extend()` 等[^2]。 #### 元组 (Tuple) 元组同样是有序的集合体,但是不可变——一旦初始化就不能更改其内部成员;不过这并不妨碍其中包含可变对象作为元素。 - **定义方式**: 圆括号 `()` 或者直接由逗号分隔多个值构成 ```python coordinates = (0, 0) single_item_tuple = ('only',) ``` - **特性** - 访问速度通常优于列表,因为不需要考虑变化带来的额外开销[^3]。 - 常被用来返回多值函数的结果或者表示固定数量的相关信息组合。 #### 字典 (Dictionary) 字典是以键值对形式存在的映射类型数据结构,每个条目都关联着唯一的键名以便快速查找对应的值。不允许存在相同名称的键。 - **定义方式**: 花括号 `{}` 加冒号 `:` 连接键与值,也可以通过 `dict()` 构造器建立 ```python person_info = {'name': 'Alice', 'age': 25} another_dict = dict(one=1, two=2) ``` - **特性** - 键必须是不可变类型的变量(如字符串、整数),而值则没有任何限制。 - 对于频繁查询特定项目的情况非常高效,平均时间复杂度接近 O(1)。 #### 集合 (Set) 集合是一个无序且不含有重复元素的独特化数组概念实现。它主要用于执行数学上的集合理论运算,像交集、并集等。 - **定义方式**: 大括号 `{}` 中放置唯一元素,或是调用 `set()` 函数 ```python unique_numbers = {1, 2, 3} from_iterable_set = set([4, 5, 6]) ``` - **特性** - 自动去除冗余项,确保所有成员都是独一无二的存在。 - 支持一系列标准集合操作符以及相应的方法来进行关系测试和转换处理。 综上所述,这些基本数据类型在实际编程过程中扮演着不可或缺的角色,理解它们之间的差异有助于编写更加简洁高效的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值