如何在for循环中调用列表项的数量

我正在编写一个 for 循环,从 pytrends 包中获取 Google Trends。现在我希望 for 循环为它在关键字列表中找到的每个关键字创建一个数据框。但我希望数据帧以列表项的编号而不是列表中的实际字符串命名。


现在这是我的代码:


from pytrends.request import TrendReq

pytrend = TrendReq(hl='de', tz=390, retries=10, backoff_factor=0.5)


keywords = ['foo', 'bar', 'dummy']


for keyword in keywords:

  try:

    pytrend.build_payload(

      kw_list=[keyword],

      geo='DE',

      timeframe = 'now 1-d')

    gbl = globals()

    gbl['df_'+[str(i) for i in range(len(keywords))]] = pytrend.interest_over_time()

    gbl['df_'+[str(i) for i in range(len(keywords))]] = gbl['df_'+[str(i) for i in range(len(keywords))]].drop(labels=['isPartial'],axis='columns')

    print(keyword + ' was succesfully pulled from Google Trends')

  except Exception as e:

    print(keyword + ' was not successfully pulled because of the following error: ' + str(e))

    continue

但不幸的是这给了我以下错误:


foo was not successfully pulled because of the following error: can only concatenate str (not "list") to str

bar was not successfully pulled because of the following error: can only concatenate str (not "list") to str

dummy was not successfully pulled because of the following error: can only concatenate str (not "list") to str

所以,我的问题是,如何获取列表中的项目编号来创建df_0、df_1、df_2等?谢谢!


收到一只叮咚
浏览 105回答 2
2回答

守着星空守着你

问题在于将字符串添加到列表中。您可能希望循环更加外部,并且您也可以使用enumarete这将为您提供一个同时包含项目及其编号的循环for i, keyword in enumerate(keywords):   gbl['df_'+str(i)] = ... something using keyword ...

开心每一天1111

from pytrends.request import TrendReqpytrend = TrendReq(hl='de', tz=390, retries=10, backoff_factor=0.5)keywords = ['foo', 'bar', 'dummy']for keyword in keywords:  try:    pytrend.build_payload(      kw_list=[keyword],      geo='DE',      timeframe = 'now 1-d')    gbl = globals()    for i in range(len(keywords)):        gbl['df_'+str(i)] = pytrend.interest_over_time()        gbl['df_'+str(i)] = gbl['df_'+str(i)].drop(labels=['isPartial'],axis='columns')    print(keyword + ' was successfully pulled from Google Trends')  except Exception as e:    print(keyword + ' was not successfully pulled because of the following error: ' + str(e))    continue我对你的代码做了一些更改并且它起作用了。这是输出。foo was successfully pulled from Google Trendsbar was successfully pulled from Google Trends dummy was successfully pulled from Google Trends上面代码的问题是您无法将列表附加到字符串。gbl['df_'+[str(i) for i in range(len(keywords))]] = pytrend.interest_over_time()gbl['df_'+[str(i) for i in range(len(keywords))]] = gbl['df_'+[str(i) for i in range(len(keywords))]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python