Skip to main content
 首页 » 编程设计

Python 在字符串中执行操作

2025年05月04日21落叶无声

所以我试图将一个变量操作(用户定义的)传递给一个函数,但在尝试找到一个好的方法时遇到了麻烦。我所能想到的就是将所有选项硬编码到函数中,如下所示:

def DoThings(Conditions): 
import re 
import pandas as pd 
d = {'time' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']), 
     'legnth' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd'])} 
df = pd.DataFrame(d) 
print df 
 
for Condition in Conditions: 
    # Split the condition into two parts 
    SplitCondition = re.split('<=|>=|!=|<|>|=',Condition) 
 
    # If the right side of the conditional statement is a number convert it to a float 
    if SplitCondition[1].isdigit(): 
        SplitCondition[1] = float(SplitCondition[1]) 
 
    # Perform the condition specified 
    if "<=" in Condition: 
        df = df[df[SplitCondition[0]]<=SplitCondition[1]] 
        print "one" 
    elif ">=" in Condition: 
        df = df[df[SplitCondition[0]]>=SplitCondition[1]] 
        print "two" 
    elif "!=" in Condition: 
        df = df[df[SplitCondition[0]]!=SplitCondition[1]] 
        print "three" 
    elif "<" in Condition: 
        df = df[df[SplitCondition[0]]<=SplitCondition[1]] 
        print "four" 
    elif ">" in Condition: 
        df = df[df[SplitCondition[0]]>=SplitCondition[1]] 
        print "five" 
    elif "=" in Condition: 
        df = df[df[SplitCondition[0]]==SplitCondition[1]] 
        print "six" 
return df 
 
# Specify the conditions 
Conditions = ["time>2","legnth<=6"] 
df = DoThings(Conditions)   # Call the function 
 
print df 

结果是:

   legnth  time 
a       4     1 
b       5     2 
c       6     3 
d       7     4 
five 
one 
   legnth  time 
c       6     3 

一切都很好,但我想知道是否有更好或更有效的方法将条件传递给函数,而无需写出所有可能的 if 语句。有什么想法吗?

解决方案:

def DoThings(Conditions): 
    import re 
    import pandas as pd 
    d = {'time' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']), 
         'legnth' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd'])} 
    df = pd.DataFrame(d) 
    print df 
 
    for Condition in Conditions: 
        # Split the condition into two parts 
        SplitCondition = re.split('<=|>=|!=|<|>|=',Condition) 
 
        # If the right side of the conditional statement is a number convert it to a float 
        if SplitCondition[1].isdigit(): 
            SplitCondition[1] = float(SplitCondition[1]) 
 
        import operator 
        ops = {'<=': operator.le, '>=': operator.ge, '!=': operator.ne, '<': operator.lt, '>': operator.gt, '=': operator.eq} 
        cond = re.findall(r'<=|>=|!=|<|>|=', Condition) 
        df = df[ops[cond[0]](df[SplitCondition[0]],SplitCondition[1])] 
 
    return df 
 
 
 
# Specify the conditions 
Conditions = ["time>2","legnth<=6"] 
df = DoThings(Conditions)   # Call the function 
 
print df 

输出:

   legnth  time 
a       4     1 
b       5     2 
c       6     3 
d       7     4 
   legnth  time 
c       6     3 

请您参考如下方法:

您可以通过 operator 模块访问内置运算符,然后构建一个将您的运算符名称映射到内置运算符的表,就像这个缩减示例一样:

import operator 
ops = {'<=': operator.le, '>=': operator.ge} 
 
In [3]: ops['>='](2, 1) 
Out[3]: True