简体   繁体   English

动态 function 使用字符串 - python

[英]dynamic function using string - python

I have seen posts similar to this but not quite.我看过类似的帖子,但不完全是。

import pandas as pd
dynamic_fun = {
    '.csv': read_csv,
    '.xlsx': read_excel
}

I would like to do something like that:我想做这样的事情:

df = pd.(dynamic_fun['.csv'])('Z:/test1.txt', delimiter = "\t")

or要么

df = pd.(dynamic_fun)['.csv']('Z:/test1.txt', delimiter = "\t")

Instead of something like that:而不是那样的东西:

df = pd.read_csv('Z:/test1.txt', delimiter = "\t")

Basically change the function dynamically using a dictionary.基本上使用字典动态更改 function。

Thank you,谢谢,

You are almost there:你快到了:

import pandas as pd
dynamic_fun = {
    '.csv': pd.read_csv,
    '.xlsx': pd.read_excel
}

df = dynamic_fun['.csv']('Z:/test1.txt', delimiter = "\t")

You need to store the complete reference to the method (including the pd. ) in the dictionary您需要在字典中存储对该方法(包括pd. )的完整引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM