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)

不言
不言forward
2018-10-11 14:08:352280browse

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.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more