python中如果需要函数返回多个值,可以返回一个包含多个值的tuple(元组),list(列表)或者dict(字典):
def profile():
name = "Danny"
age = 30
return (name, age)
profile_data = profile()
print(profile_data[0])
# Output: Danny
print(profile_data[1])
# Output: 30或者按照更常见的惯例:
def profile():
name = "Danny"
age = 30
return name, age
profile_name, profile_age = profile()
print(profile_name)
# Output: Danny
print(profile_age)
# Output: 30当然也可以使用具名元组(namedtuple):
from collections import namedtuple
def profile():
Person = namedtuple('Person', 'name age')
return Person(name="Danny", age=31)
# Use as namedtuple
p = profile()
print(p, type(p))
# Person(name='Danny', age=31)
print(p.name)
# Danny
print(p.age)
#31
# Use as plain tuple
p = profile()
print(p[0])
# Danny
print(p[1])
#31
# Unpack it immediatly
name, age = profile()
print(name)
# Danny
print(age)
#31 | 留言与评论(共有 0 条评论) “” |