如何仅使用函数中的一个返回变量

时间:2017-04-29 23:57:19

标签: python function

这可能是一个愚蠢的问题,但我找不到答案。

我使用Flask / Python并且有一个名为' hero.py'的.py文件。包含dict ex。

heroes = {'ironman': 'Strength, Covert', 'IronFist': 'Tech, Strenght'}

def hero():
    hero, attribute = random.choice(list(heroes.items()))
    if 'Tech' not in attribute:
        hero, attribute = random.choice(list(heroes.items()))
    if 'Tech' in attribute:
        return(hero, attribute)

我想知道在调用函数时如何仅使用attribute变量?

我可以做类似的事情:

my_hero = hero()
print(my_hero)

但是如何只打印出那个英雄的属性呢?希望这有意义吗?

2 个答案:

答案 0 :(得分:2)

如果您有一个返回可转换数据(如元组或列表)的函数,则可以通过多种方式将包含值集合分配给变量:

def my_function():
    return ('a', 'b')

您可以将返回值分配给单个变量:

example_1 = my_function()

>>> example_1
('a', 'b')

或者您可以将其分配给多个变量,与对象中的值数量相匹配:

example_2a, example_2b = my_function()

>>> example_2a
'a'

>>> example_2b
'b'

如果你只需要一个的值,而不是另一个,一个常见的形式是将不需要的值分配给_,这被视为标准一次性:

_, example_3 = my_function()

即使您拥有大量的价值并希望抛弃多个价值观,这仍然有效:

def my_next_function():
    return ('a', 'b', 'c', 'd', 'e')

_, example_4, _, _, _ = my_next_function()

>>> example_4
'b'

当然,您也可以简单地进行位置分配,例如:

example_5 = my_function()[1]

然而,我更喜欢_方法,因为我认为它使意图更清晰 - 也就是说,它明确告诉读者你只关心一个值而不关心其他值。但是每个人都有自己的

答案 1 :(得分:1)

print(hero()[0])应该适用于第一个属性

相关问题