[英]Python recognise with and without quotation marks
I have this line of code that works.我有这行代码有效。
price = df1.loc[:, ['price', 'date']]
I need to emulate this is as a loop with other metrics like sales and revenue.我需要将其模拟为与销售和收入等其他指标的循环。 Is this possible?
这可能吗? ie How do I get Python to reference a word in the list both with and without quotation marks?
即,如何让 Python 引用列表中带引号和不带引号的单词?
listx = [price,sales, revenue]
for a in listx:
a = df1.loc[:, ['a', 'date']]
IIUC, you could do something like this, using a list comprehension: IIUC,你可以做这样的事情,使用列表理解:
listx = ['price','sales', 'revenue']
price, sales, revenue=[df1.loc[:, [a, 'date']] for a in listx]
For a general way, this could be an approach using globals
:一般来说,这可能是一种使用
globals
的方法:
listx = ['price','sales', 'revenue']
for a in listx:
globals().update({a:df1.loc[:, [a, 'date']]})
As is requested in the comments, please provide a minimal reproducible example in the future.根据评论中的要求,请在未来提供一个最小的可重现示例。
One way to do it is to save it in a dict:一种方法是将其保存在字典中:
metrics = {}
listx = ['price', 'sales', 'revenue']
for a in listx:
metrics[a] = df1.loc[:, [a, 'date']]
Now you can access the metrics with metric['sales']
etc.现在您可以使用
metric['sales']
等访问指标。
Maybe I misunderstood your question.也许我误解了你的问题。 Please provide a minimal reproducible example in the future.
请在将来提供一个最小的可重现示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.