Stackoverflow, hello. I didn't found any information about exporting a data (list in my case) from a "function"
The end of my code is:
def namesearch():
with open ('recipes.txt') as f:
dishnames = []
for line in f:
line = line.strip()
# print (line)
line2=line.split()
if len(line2) <= 3:
pass
try:
a=(int(line2[0])/1)
except IndexError:
pass
except ValueError:
dishnames.append(line2)
for i in dishnames:
if len(i) > 1:
j=' '.join(i)
else:
j = str(i[0])
dishnames_string.append(j)
namesearch()
def search_ingridientsnames():
with open('recipes.txt') as f:
ingridient_names = []
for line in f:
line = line.strip()
# print (line)
line2 = line.split()
try:
i=0
if len(line2) > 3 or len(line2)<1:
ingridient_names.append(line2[0])
except IndexError:
ingridient_names.append('_')
# print(ingridient_names)
ingridient_names_final=[i.split(',') for i in ','.join(ingridient_names).split(',_,')]
print(ingridient_names_final)
search_ingridientsnames()
print (dishnames_string)
print (ingridient_names_final)
The result is
>> [['Egg', 'Milk', 'Tomato'], ['Duck', 'Water', 'Honey', 'Soy'], ['Potato', 'Garlic', 'Gouda'], ['Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']]
>> ['Omelette', 'Peking Duck', 'Baked potato', 'Fajitos']
[]
Do you see that? The first print(ingridient_names_final)
in the end of function - writing the list from function and it's ok. As you see, I have another value from function, print (dishnames_string)
, which is also a part of function - the result of the work is the list. However, when I print again the value from function print (search_ingridientsnames)
- the result is []. And I even can't write print(list(search_ingridientsnames)) - the result is an error. How could I recieve the same result from function launching?
The result should be:
>> [['Egg', 'Milk', 'Tomato'], ['Duck', 'Water', 'Honey', 'Soy'], ['Potato', 'Garlic', 'Gouda'], ['Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']]
>> ['Omelette', 'Peking Duck', 'Baked potato', 'Fajitos']
>> [['Egg', 'Milk', 'Tomato'], ['Duck', 'Water', 'Honey', 'Soy'], ['Potato', 'Garlic', 'Gouda'], ['Beef', 'Sweet', 'Pita', 'Wine', 'Tomato']]
UPD
The code is printing exactly what you asked for. To print the result of the function you need to use:
print (search_ingridientsnames())
From a first hand look i can say that python is interpreting the result of the print statement as an object and is therefore printing what you see on the console. You need to write it as print(search_ingredientsname()).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.