search
HomeBackend DevelopmentPython TutorialHow to decompose iterable objects into separate variables in Python (code)

What this article brings to you is about the implementation method (code) of decomposing iterable objects into separate variables in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

1. Requirements

Now you have a tuple or sequence containing N elements, and now you want to decompose it into N separate variables.

2. Solution

In python, any sequence, tuple, or serializable object can be decomposed into separate objects through a simple assignment operation. variable.

The only requirement is that the total number and structure of variables must match the sequence. If it does not match, an error will be reported

Example display:

#将序列分解为单独的变量
m=(1,2)
x,y=m
print("x=",x)
print("y=",y)

print("*"*30)

data=["mark",18,"超级帅",(1992,5,4)]
name,age,feature,birthday=data
print("name=",name)
print("age=",age)
print("feature=",feature)
print("birthday=",birthday)
print("*"*30)


name,age,feature,(year,mon,day)=data
print("name=",name)
print("age=",age)
print("feature=",feature)
print("year=",year)
print("mon=",mon)
print("day=",day)

Result

x= 1
y= 2
******************************
name= mark
age= 18
feature= 超级帅
birthday= (1992, 5, 4)
******************************
name= mark
age= 18
feature= 超级帅
year= 1992
mon= 5
day= 4

3. Thinking

is actually not just A list of tuples can perform decomposition operations as long as the object is iterable, including strings, files, iterators, and generators.

Example display:

#将序列分解为单独的变量
mark="mark"
m,a,r,k=mark
print(m)
print(a)
print(r)
print(k)
print("*"*30)

#有时候我们想丢弃某个值,单由于变量数量必须和要分解的对象的可分解数量相同,此时我们可以使用_来表示要丢弃的值。

mark="mark"
m,a,r,_=mark
print(m)
print(a)
print(r)
#其实_还是一个变量,指示看起来舒服点
print(_)

Result:

m
a
r
k
******************************
m
a
r
k

4. Requirement upgrade

If the serial number object can be decomposed into N elements, do we have to create N elements? What if the value of N is very large?

5. Solution upgrade

The "*expression" in Python can meet the above needs. For example, there are countless grade lists: grades. Now I want to remove the first grade and the last grade, and then find the average of the remaining grades:

Code

import numpy as np

grades=list(range(10))#定义一个0-999的分数列表
print("grades:"+str(grades))
first,*middle,last=grades
print("middle:"+str(middle))
print("去掉第一个和最后一个分数后的平均值:"+str(np.mean(middle)))

Result

grades:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
middle:[1, 2, 3, 4, 5, 6, 7, 8]
去掉第一个和最后一个分数后的平均值:4.5

Of course, this [*expression] can be located at the first position, the last position, or other positions.

Suppose there are some user records. The records consist of names and email addresses, followed by any number of phone numbers:

record=('mark','1782980833@qq.com','18321859453','18956245389')
name,email,*phone_numbers=record

print(name)
print(email)
print(phone_numbers)

Run results:

mark
1782980833@qq.com
['18321859453', '18956245389']

6 , *Expression skills

*Expressions are especially useful when iterating over a variable-length sequence of tuples

Code:

records=[
    ('foo',1,2),
    ('bar','hello'),
    ('foo',3,4),
]

def do_foo(x,y):
    print('foo',x,y)

def do_bar(s):
    print('bar',s)

for tag,*args in records:
    if tag=='foo':
        do_foo(*args)
    elif tag=='bar':
        do_bar(*args)

Result:

foo 1 2
bar hello
foo 3 4

Also useful when combined with certain string processing operations (such as splitting)

Code:

line='nobody:*:-2:-2:unp user:/var/empty:/user/nim/false'

uname,*fileds,homedir,sh=line.split(':')
print(uname)
print(homedir)
print(sh)

Result:

nobody
/var/empty
/user/nim/false

The above is the detailed content of How to decompose iterable objects into separate variables in Python (code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.