【问题标题】:What does return['string'] do?return['string'] 有什么作用?
【发布时间】:2016-07-20 17:52:55
【问题描述】:

以下代码块摘自以下论坛Programmatically searching google in Python using custom search

from googleapiclient.discovery import build
import pprint

my_api_key = "Google API key"
my_cse_id = "Custom Search Engine ID"

def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res['items']

results = google_search(
    'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id, num=10)
for result in results:
    pprint.pprint(result)

在函数google_search 中,我无法理解当res 返回为res['items'] 而只是res 时会发生什么以及发生了什么。

编辑:也许显示更改两个变体的结果会有所帮助。

当使用res['items'] 时,results 是一个包含 10 个值的字典,每个值包含 11 个项目。

当只使用res 时,results 是一个包含 6 个项目的字典,每个项目包含不同数量的项目和数据结构。

【问题讨论】:

  • 看起来像键值类型排列。使用键“字符串”获取条目的值。非常直接。
  • 提示:return 与此无关。 res['items'] 只是另一个产生结果的表达式。
  • 您可能想阅读Python tutorial;我将您直接链接到使用该语法的部分;你可能想start at the beginning

标签: python return


【解决方案1】:

它返回变量res中那个键的值。

想象一个像下面这样的数据结构:

{
    "errors": [],
    "items": [ "item1", "item2", "item3"],
    "status": "success"
}

这是一个常规的 Python 字典,您现在可以在项目中使用它。如果res 是对该字典的引用,则以下内容为真:

res['items'] == [ "item1", "item2", "item3"]

换句话说,它将返回字典中该索引指示的数组。对于命名索引,它基本上等同于 res[0]

【讨论】:

  • 我不经常使用字典,但这很有意义!
【解决方案2】:

我的猜测是 res 是一个字典对象。返回res['items'] 将返回与字典对象res 中的键'items' 一起存储的值。

【讨论】:

    【解决方案3】:

    res 是一个字典,这里是它可能包含的示例:

    res = {
        'item_count': 50, 
        'items': ['item1', 'item2', 'item3'],
        'search' : 'search terms here'
    }
    

    如果您返回res,那么您将在结果中得到所有内容。在我的示例中,您可以访问 item_count 并获取结果数。

    返回res['items'],您将仅获得导致您的查询的项目列表。

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 2016-05-30
      • 2014-05-24
      • 2020-08-23
      • 2011-08-26
      • 2013-11-12
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      相关资源
      最近更新 更多