为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

收到一只叮咚 2023-07-05 17:53:55
我正在编写一个 for 循环,从 pytrends 包中获取 Google Trends。现在我希望 for 循环为它在关键字列表中找到的每个关键字创建一个数据框。但我希望数据帧以列表项的编号而不是列表中的实际字符串命名。现在这是我的代码: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()    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 strbar was not successfully pulled because of the following error: can only concatenate str (not "list") to strdummy was not successfully pulled because of the following error: can only concatenate str (not "list") to str所以,我的问题是,如何获取列表中的项目编号来创建df_0、df_1、df_2等?谢谢!
查看完整描述

2 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

问题在于将字符串添加到列表中。

您可能希望循环更加外部,并且您也可以使用enumarete这将为您提供一个同时包含项目及其编号的循环

for i, keyword in enumerate(keywords):
  gbl['df_'+str(i)] = ... something using keyword ...


查看完整回答
反对 回复 2023-07-05
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

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()

    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 Trends

bar 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))]]




查看完整回答
反对 回复 2023-07-05
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信