Как возврат является выводом функции, отличающейся от печати его?

Вы забыли добавить группировку к вашему запросу:

GROUP BY Trip_T.tripID, Trip_T.title, User_T.username

Таким образом, счетчики соответствуют каждому триплету из (Trip_T.tripID, Trip_T.title, User_T.username)

33
задан kindall 27 November 2017 в 18:38
поделиться

4 ответа

Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:

def autoparts():
  parts_dict = {}
  list_of_parts = open('list_of_parts.txt', 'r')
  for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v
  return parts_dict

Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:

my_auto_parts = autoparts() 
print(my_auto_parts['engine']) 

See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.

For a good tutorial, check out dive into python. It's free and very easy to follow.

63
ответ дан cricket_007 27 November 2019 в 17:55
поделиться

Оператор print выведет объект для пользователя. Оператор return позволит присвоить словарь переменной после завершения функции .

>>> def foo():
...     print "Hello, world!"
... 
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
...     return "Hello, world!"
... 
>>> a = foo()
>>> a
'Hello, world!'

Или в контексте возврата словаря:

>>> def foo():
...     print {'a' : 1, 'b' : 2}
... 
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
...     return {'a' : 1, 'b' : 2}
... 
>>> a = foo()
>>> a
{'a': 1, 'b': 2}

(Операторы, в которых после строки ничего не выводится выполнено означает, что последний оператор вернул None)

8
ответ дан Jason Baker 27 November 2019 в 17:55
поделиться

Я думаю, что вы запутались, потому что вы бежите из REPL, который автоматически выводит значение, возвращаемое, когда вы вызвать функцию. В этом случае вы получите идентичный вывод независимо от того, есть ли у вас функция, которая создает значение, печатает его и выбрасывает, или у вас есть функция, которая создает значение и возвращает его, позволяя REPL распечатать его.

Однако, это совсем не одно и то же, что вы поймете, когда будете вызывать autoparts с другой функцией, которая хочет что-то сделать со значением, которое создает autoparts.

4
ответ дан RossFabricant 27 November 2019 в 17:55
поделиться

you just add a return statement...

def autoparts():
  parts_dict={}
  list_of_parts = open('list_of_parts.txt', 'r')
  for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v
  return parts_dict

printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:

return parts_dict, list_of_parts

to use it:

test_dict = {}
test_dict = autoparts()
3
ответ дан jle 27 November 2019 в 17:55
поделиться
Другие вопросы по тегам:

Похожие вопросы: