Python基础小知识问答系列-可迭代型变量赋值

1. 问题:

  • 怎样简洁的把列表中的元素赋值给单个变量?
  • 当需要列表中指定几个值时,剩余的变量都收集在一起,该怎么进行变量赋值?
  • 当只需要列表中指定某几个值,其他值都忽略时,该怎么进行变量赋值?

2. 解决方法:

  • 示例:
python 复制代码
test_list = [1 ,3 ,6 ,2 ,9]

# 一对一赋值
x, y, z, m, n = test_list
print(f"一一赋值输出:{x}, {y}, {z}, {m}, {n}")

# 收集赋值
x, *y, z = test_list
print(f"一对多赋值输出:{x}, {y}, {z}")

# 丢弃型赋值
_, x, y, _, z = test_list
print(f"丢弃部分内容赋值:{x}, {y}, {z}")
  • 示例结果:
相关推荐
Warson_L8 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅8 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅8 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L8 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅8 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L9 小时前
python的类&继承
python
Warson_L9 小时前
类型标注/type annotation
python
ThreeS11 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵13 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏