重复调用def,怎么获取所有结果?

import random
def get_page(has=False):
    text={'title':has,'has_more':random.randint(0,9)}
    if text['has_more']:
        get_page(text['has_more'])
        print(text)
    return text
print('所有结果',get_page(1))

这种写法,有什么方法可以获取所有结果不!

Jason990420
最佳答案

个人意见

  1. get_page 的参数应该永远不为0, 所以应该是 has=True
  2. 要获取全部的结果, 所以采用列表来存所有的结果
  3. 该函数, 要回传的结果, 应该就是这次的结果, 加上后面的结果, 所以是列表相加
  4. 每一项打印的顺序要同列表一样, 就必须放在取得下次结果之前.
import random

def get_page(has=True):
    text={'title':has,'has_more':random.randint(0,9)}
    if text['has_more']:
        print(text)
        next_one = get_page(text['has_more'])
    else:
        next_one = []
    return [text] + next_one

print(get_page(1))

比较直接的方式, 应该如下,

import random

def get_page(has=True):
    if not has:
        return []
    more = random.randint(0,9)
    text = {'title':has,'has_more':more}
    print(text)
    return [text] + get_page(more)

print(get_page(1))

递归的基本方式如下

def 函数(变量=预设初始值):
    if 已达到临界值:
        return 临界值的结果
    处理本次的内容
    return 本次结果 以及 再调用函数所得的下次结果
2年前 评论
heavenm (楼主) 2年前
讨论数量: 1
Jason990420

个人意见

  1. get_page 的参数应该永远不为0, 所以应该是 has=True
  2. 要获取全部的结果, 所以采用列表来存所有的结果
  3. 该函数, 要回传的结果, 应该就是这次的结果, 加上后面的结果, 所以是列表相加
  4. 每一项打印的顺序要同列表一样, 就必须放在取得下次结果之前.
import random

def get_page(has=True):
    text={'title':has,'has_more':random.randint(0,9)}
    if text['has_more']:
        print(text)
        next_one = get_page(text['has_more'])
    else:
        next_one = []
    return [text] + next_one

print(get_page(1))

比较直接的方式, 应该如下,

import random

def get_page(has=True):
    if not has:
        return []
    more = random.randint(0,9)
    text = {'title':has,'has_more':more}
    print(text)
    return [text] + get_page(more)

print(get_page(1))

递归的基本方式如下

def 函数(变量=预设初始值):
    if 已达到临界值:
        return 临界值的结果
    处理本次的内容
    return 本次结果 以及 再调用函数所得的下次结果
2年前 评论
heavenm (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!