返回素食主义者名单

时间:2016-02-28 05:53:27

标签: python-3.x

def vegan(something):

    list of Foods is returned  
   data = []
   for line in something:
       if line.is_vegan == True:
        data.append(line)
   return data 

如何将其变成递归函数,我尝试的任何东西都会让它变得更糟,这是旧函数。

3 个答案:

答案 0 :(得分:0)

希望这有帮助,

veggie= [] 
counter = 0
def foodie(counter, foods):
    if counter < len(foods):
        if foods[counter].split("|")[2] == 'True':
            veggie.append(foods[counter])
        counter = counter + 1
        foodie(counter, foods)
    else:
        return; 

foodie(foods)

谢谢,

答案 1 :(得分:0)

一个简单的版本可能是:

def veggies(foods):
  if not foods:
    return []
  if foods[0].is_vegetarian:
    return [foods[0]] + veggies(foods[1:])
  return veggies(foods[1:])

基本上你处理第一个元素,然后将其余元素传递给函数的下一个调用,直到没有元素。

答案 2 :(得分:0)

这是另一种方式

f = open("foods.txt",'r')

def doStuff(f):
    line = f.readline()
    if line: # While there are lines to read, readline
        if "True" in line:
            print(line)
            # Do formatting and storing into object here
        doStuff(f)

doStuff(f)