如何在python3中返回像print这样的多个值?

2024-06-08 16:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我使用print,它会给我101238157和None。你知道吗

i = 0
while i < 3:
  champion = matchList['matches'][i]['champion']
  i = i + 1
  print(champion)

但如果我使用RETURN,它只返回101。 那我该怎么办?你知道吗


Tags: nonereturnprintmatcheswhilechampionmatchlist
3条回答

有多种方法,但下面是使用range和for循环的更简单的方法。数据将是您的输出列表。你也可以试试

data=[matchList['matches'][i]['champion'] for i in range(3)]

return只能有一个值(可以是列表之类的对象或其他对象)。。。为什么?因为return是假定函数的值。例如,当你对一个函数赋值时

def champs()
     return MJ KD LBJ

champ = champs()

这样,数字应该是MJ,KD和LBJ在同一时间。。。从概念上讲是不可能的。但我们可以退回一份名单!你知道吗


首先使用for循环,更紧凑易读,并且做同样的事情:

for i in range(3):
    champion = matchList['matches'][i]['champion']
    print(champion)

现在使用冠军名单:

champions = []
for i in range(3):
    champion = matchList['matches'][i]['champion']
    champions.append(champion)
    print (champion)

以更紧凑的方式:

champions = []
for i in range(3):
    champions.append(matchList['matches'][i]['champion'])
    print(champions)

现在可以用func返回:

    def getChamp(matchList):
        champions = []
        for i in range(3):
            champions.append(matchList['matches'][i]['champion'])
        return champions

也许您希望使for循环更具动态性:

def getChamp(matchList):
        champions = []
        for match in range(len(matchList['matches'])):
            champions.append(matchList['matches'][match]['champion'])
        return champions

这是一种更像Python的方式

def getChamp(matchList):
        for match in matchList['matches']:
            yield match['champion']
        yield None

我希望这就是你需要做的!你知道吗

将所有值添加到一个变量并返回它。你知道吗

def get_my_value():
    values = []
    for i in range(3):
        champion = matchList['matches'][i]['champion']
        values.append(champion)
    return values

data = get_my_value()

相关问题 更多 >