序列解包

 序列解包:  *针对可迭代对象的解包    ** 针对字典的 解包

  格式:变量a,变量b....(多个变量)= 可迭代对象

案例:  info = "guohan|222|20"  a,b,c = info.split("|")     info.split("|")成为列表:可迭代  将guohan    222    20 赋值给a b c

      比如将info以|分割后的元素变成字典的value:    

info = "guohan|123|20"
name,pwd,age = info.split("|")
a = {"Name":name,"Pwd":pwd,"Age":age}  #变量的使用在其定义后前即不可以将2 3两行换位置
print(a)
>>>{'Name': 'guohan', 'Pwd': '123', 'Age': '20'}

列表元组解包:

# 列表解包
data = [10, 20, 30]
a, b, c = data
print(a)  # 输出: 10
print(b)  # 输出: 20
print(c)  # 输出: 30

# 元组解包
info = ("Alice", 25, "Engineer")
name, age, job = info
print(name)  # 输出: Alice
print(age)   # 输出: 25
print(job)   # 输出: Engineer

字符串解包:

text = "ABC"
x, y, z = text
print(x)  # 输出: A
print(y)  # 输出: B
print(z)  # 输出: C

解包时忽略部分元素:如果只需要序列中部分元素  可以用_进行占位忽略掉部分元素

data = [1, 2, 3, 4, 5]
first, _, third, _, fifth = data
print(first)  # 输出: 1
print(third)  # 输出: 3
print(fifth)  # 输出: 5

解包不定长度的序列:用*捕获多个元素(会被打包成列表),其余元素按顺序赋值

# 捕获前两个元素,剩余元素给 rest
numbers = [1, 2, 3, 4, 5]
a, b, *rest = numbers
print(a)    # 输出: 1
print(b)    # 输出: 2
print(rest) # 输出: [3, 4, 5]

# 捕获中间元素
data = ["Alice", 25, "Engineer", "New York"]
name, *details, city = data
print(name)    # 输出: Alice
print(details) # 输出: [25, "Engineer"]
print(city)    # 输出: New York

 

关于* / **

*

* 是 Python 的序列解包运算符(对应 ** 字典解包),专门用于列表、元组、字符串等可迭代对象,核心作用是:把可迭代对象 “拆成单个元素”,直接平铺使用。

1. 函数传参(位置参数平铺)

适合函数需要多个独立位置参数时,直接传序列解包:
# 有个列表(可迭代对象)
nums = [10, 20, 30]

# 定义函数,需要3个位置参数
def sum_num(a, b, c):
    return a + b + c

# 序列解包传参(等价于 sum_num(10, 20, 30))
result = sum_num(*nums)
print(result)  # 输出:60

2. 合并序列(列表 / 元组拼接)

不用写 extend() 或 +,直接解包合并:
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# 解包合并成新列表(等价于 [1,2,3,4,5,6])
new_list = [*list1, *list2]
print(new_list)  # 输出:[1, 2, 3, 4, 5, 6]

# 元组也能这么用
tuple1 = (10, 20)
tuple2 = (30, 40)
new_tuple = (*tuple1, *tuple2)
print(new_tuple)  # 输出:(10, 20, 30, 40)

3. 字符串解包(拆成单个字符)

字符串也是可迭代对象,* 会拆成每个字符:
s = "abc"
new_list = [*s]  # 等价于 ['a', 'b', 'c']
print(new_list)  # 输出:['a', 'b', 'c']

避坑提醒

* 不能解包字典(会默认解包字典的 key):
user = {'name': '张三', 'age': 20}
print(*user)  # 输出:name age(只拆 key,不拆 value)

核心记住 3 点:

  • 用 * 开头,只针对可迭代对象(列表、元组、字符串等);
  • 解包后是单个独立元素(平铺格式);
  • 不能单独写 *对象(会报错),必须跟在函数括号里或容器大括号里(列表 / 元组 / 集合)。

 

**

字典解包(** 语法)一句话总结:把字典 {'key1': val1, 'key2': val2} 拆成 key1=val1, key2=val2 的形式,只能用在「函数传参」或「合并字典」里。

1. 函数传参(Flask 模板用的场景 render_template('login.html',**locals()))

# 有个字典
user = {'name': '张三', 'age': 20}

# 定义一个函数,需要 key=value 形式的参数
def print_user(name, age):
    print(f"姓名:{name},年龄:{age}")

# 字典解包传参(等价于 print_user(name='张三', age=20))
print_user(**user)  # 输出:姓名:张三,年龄:20

2. 合并字典

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# 解包合并(等价于 {'a':1, 'b':2, 'c':3, 'd':4})
new_dict = {**dict1, **dict2}
print(new_dict)  # 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4}
核心记住 3 点:
  • 用 ** 开头,只针对字典;
  • 解包后是 key=value 格式;
  • 不能单独写 **字典(会报错),必须跟在函数括号里或字典大括号里。

 

 

image

 

 

 

题目:函数的定义+数据类型+序列解包

微信图片_20250929203812_20_2

#打开文件并指定格式函数
#打开文件并指定格式函数
def get_file(file_path):
    a_list = list()
    with open(file_path,"r",encoding = "utf-8") as result:
        for line in result:
            line.strip()
            a_list.append(line.strip())
    print(a_list)
def get_file1(file_path):
    a_list = list()
    with open(file_path,"r",encoding = "utf-8") as result:
        for line in result:
            line.strip().split("|")
            a_list.append(line.strip().split("|"))
    print(a_list)
def get_file2(file_path):
    a_list = list()
    with open(file_path,"r",encoding = "utf-8") as result:
        for line in result:
            line.strip().split("|")
            name,pwd,age = line.strip().split("|")
            data = {"Name":name,"Pwd":pwd,"Age":age}
            a_list.append(data)
    print(a_list)
get_file("np.txt")
get_file1("np.txt")
get_file2("np.txt")
posted @ 2025-09-29 19:50  guohan  阅读(25)  评论(0)    收藏  举报