Python函数:变量和字符串 [英] Python function: variable and string

查看:107
本文介绍了Python函数:变量和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下公式来检查(感谢您的帮助

 查询= ['狗','猫','仓鼠'] 

def get_trends(queries):
return pd.concat([pytrend.trend({'q':x,'date':'01 / 2015 12m'},return_type ='dataframe')
for query in],axis = 1)

get_trends(queries)

此函数为列表中的每个项目启动Google Trends查询,并将返回的数据框放在一起。我现在需要做的是做同样的事情,但每个查询中都有一个静态变量(pet)。



例如,没有公式的查询会$ p
$ b $ p $ 返回pytrend.trend({'q':'pet,dog','date':'01 / 2015 12m '},return_type ='dataframe')

我知道我可以试试

 查询= ['宠物,狗','宠物,猫','宠物,仓鼠'] 

但也许有一种更优雅的方式?



我试过了

  static = ['pet'] 
返回pytrend.trend({'q':'''+ static + x +''','' date':'01 / 2015 12m'},return_type ='dataframe')

但不是

解决方案

您可以这样做:

  In [54]:%paste 
static ='animals'
animals = ['dog','cat','仓鼠']
查询= ['{},{}'。format(static,x)for x in animals]
## - 结束粘贴文本 -

In [55]:queries
Out [55]:['动物,狗','动物,猫','动物,仓鼠']

现在您可以将查询传递给您的函数:

  get_trends(查询)


I have following formula to check (Thanks for helping me on this!).

queries = ['dog','cat','hamster']

    def get_trends(queries):
        return pd.concat([pytrend.trend({'q': x, 'date': '01/2015 12m'}, return_type='dataframe')
    for x in queries], axis=1)

get_trends(queries)

This function fires a Google Trends query for each item in the list and puts the returning dataframes next to each other. What I need to do now is to do exactly the same, but have each one static variable (pet) in the query.

For example, a query without the formula would be

return pytrend.trend({'q': 'pet, dog', 'date': '01/2015 12m'}, return_type='dataframe')

I know I could try

queries = ['pet, dog','pet, cat','pet, hamster']

But maybe there's a more elegant way?

I tried

static =['pet']
return pytrend.trend({'q': ''' + static + x + ''', 'date': '01/2015 12m'}, return_type='dataframe')

but wasn't successful with that.

解决方案

You can do it this way:

In [54]: %paste
static = 'animals'
animals = ['dog','cat','hamster']
queries = ['{}, {}'.format(static, x) for x in animals]
## -- End pasted text --

In [55]: queries
Out[55]: ['animals, dog', 'animals, cat', 'animals, hamster']

now you can pass queries to your function:

get_trends(queries)

这篇关于Python函数:变量和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆