【问题标题】:iterating over function and storing all of the results in a variable?迭代函数并将所有结果存储在变量中?
【发布时间】:2012-09-19 12:21:38
【问题描述】:

这可能是一个非常简单的问题,但是当您迭代一个函数时,如何将所有结果存储在一个变量中,因为每当我这样做时,该变量只存储第一个结果?

for a in hometimeline['ids']:
   b = oauth_req(
    'https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&user_id=%s'%a,
   '###########################################',  (these are just tokens)
   '###########################################')

谢谢

【问题讨论】:

    标签: python function variables


    【解决方案1】:

    使用列表

    b = []
    for a in hometimeline['ids']:
       b.append(oauth_req(
          'https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&user_id=%s'%a,
          '###########################################',  (these are just tokens)
          '###########################################'))
    

    或字典

    b = {}
    
    for a in hometimeline['ids']:
       b[a] = oauth_req(
          'https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&user_id=%s'%a,
          '###########################################',  (these are just tokens)
          '###########################################')
    

    【讨论】:

      【解决方案2】:

      使用列表推导:

      b=[oauth_req("some_parameters_here%s",a) for a in hometimeline['ids']]
      

      【讨论】:

      • 这个列表理解是多余的。我想你在找[function(x) for x in hometimeline['ids']]
      猜你喜欢
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2018-06-07
      • 2021-12-16
      相关资源
      最近更新 更多