Home > Backend Development > Python Tutorial > How to decompose iterable objects into separate variables in Python (code)

How to decompose iterable objects into separate variables in Python (code)

不言
Release: 2018-10-11 14:09:43
forward
2291 people have browsed it

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)
Copy after login

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
Copy after login

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(_)
Copy after login

Result:

m
a
r
k
******************************
m
a
r
k
Copy after login

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)))
Copy after login

Result

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

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)
Copy after login

Run results:

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

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)
Copy after login

Result:

foo 1 2
bar hello
foo 3 4
Copy after login

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)
Copy after login

Result:

nobody
/var/empty
/user/nim/false
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template