Python 3.x 返回纯素食者列表
如何将其转换为递归函数,我尝试的任何操作都会使其变得更糟,这是较旧的函数。希望这有帮助Python 3.x 返回纯素食者列表,python-3.x,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 veggie=[] 计数器=0 def foodie(柜台、食品): 如
def vegan(something):
list of Foods is returned
data = []
for line in something:
if line.is_vegan == True:
data.append(line)
return data
veggie=[]
计数器=0
def foodie(柜台、食品):
如果柜台
谢谢,一个简单的版本可以是:
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)
基本上,处理第一个元素,然后将其余元素传递给函数的下一个调用,直到没有元素为止。这里是另一种方法
def veggies(foods):
if not foods:
return []
if foods[0].is_vegetarian:
return [foods[0]] + veggies(foods[1:])
return veggies(foods[1:])
递归循环的通常方法是让函数处理第一个参数,然后返回该参数,再加上对同一个函数的调用,而列表的其余部分则不起作用。(提示:什么类型的食物是
foods[counter].split(“|”)返回?@njzk2谢谢您的通知。。。这是未经测试的代码…:)非常感谢,我现在明白多了。
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)