英文:
Python: How can I use a String for a If-Statement?
问题
以下是您要的翻译内容:
In Python I have to build a (long) if statement dynamically.
How can I do this?
我需要在Python中动态构建一个(较长的)if语句。
我该如何做?
I tried the following test code to store the necessary if-statement within a string with the function "buildFilterCondition".
But this doesn't work...
我尝试了以下测试代码,使用函数"buildFilterCondition"将必要的if语句存储在字符串中。但这并不起作用...
Any ideas? What is going wrong?
Thank you very much.
有什么想法吗?出了什么问题?
非常感谢。
Input = [1,2,3,4,5,6,7]
Filter = [4,7]
FilterCondition = ""
Input = [1,2,3,4,5,6,7]
Filter = [4,7]
FilterCondition = ""
def buildFilterCondition():
global FilterCondition
for f in Filter:
FilterCondition = FilterCondition + "(x==" + str(f) + ") | "
#remove the last "| " sign
FilterCondition = FilterCondition[:-2]
print("Current Filter: " + FilterCondition)
buildFilterCondition()
for x in Input:
if( FilterCondition ):
print(x)
def buildFilterCondition():
global FilterCondition
for f in Filter:
FilterCondition = FilterCondition + "(x==" + str(f) + ") | "
#移除最后的"| "符号
FilterCondition = FilterCondition[:-2]
print("当前过滤条件: " + FilterCondition)
buildFilterCondition()
for x in Input:
if( FilterCondition ):
print(x)
With my Function buildFilterCondition() I want to reach the following situation, because the function generates the string "(x==4) | (x==7)", but this doesn't work:
使用我的函数buildFilterCondition(),我想达到以下情况,因为该函数生成字符串"(x==4) | (x==7)",但这不起作用:
for x in Input:
if( (x==4) | (x==7) ):
print(x)
The output, the result should be 4,7 (--> filtered)
输出,结果应该是4,7(-->已过滤)
The background of my question actually had a different intention than to replace an if-statement.
我的问题的背景实际上有一个不同的意图,不是要替代if语句。
I need a longer multiple condition to select specific columns of a pandas dataframe.
我需要一个更长的多重条件来选择pandas数据框的特定列。
For example:
例如:
df2=df.loc[(df['Discount1'] == 1000) & (df['Discount2'] == 2000)]
df2=df.loc[(df['Discount1'] == 1000) & (df['Discount2'] == 2000)]
I wanted to keep the column names and the values (1000, 2000) in 2 separate lists (or dictionary) to make my code a little more "generic".
我想将列名和值(1000、2000)分别保存在两个列表(或字典)中,以使我的代码更加“通用”。
colmnHeader = ["Discount1", "Discount2"]
filterValue = [1000, 2000]
colmnHeader = ["Discount1", "Discount2"]
filterValue = [1000, 2000]
To "filter" the data frame, I then only need to adjust the lists.
然后,我只需要调整列表来“过滤”数据框。
How do I now rewrite the call to the .loc method so that it works for iterating over the lists?
现在,我该如何重写对.loc方法的调用,以使其适用于对列表进行迭代?
df2=df.loc[(df[colmnHeader[0] == [filterValue[0]) & (df[colmnHeader[1]] == filterValue[1])]
df2=df.loc[(df[colmnHeader[0] == [filterValue[0]) & (df[colmnHeader[1]] == filterValue[1])]
Unfortunately, my current attempt with the following code does not work because the panda-loc function has not to be called sequentially, but in parallel.
不幸的是,我的当前尝试与以下代码不起作用,因为pandas的.loc函数不需要按顺序调用,而是并行调用。
#FILTER
colmn = ["colmn1", "colmn2", "colmn3"]
cellContent = ["1000", "2000", "3000"]
first make sure, the lists have the same size
if( len(colmn) == len(cellContent)):
curIdx = 0
for curColmnName in colmn:
df_columns= df_columns.loc[df_columns [curColmnName]==cellContent[curIdx]]
curIdx += 1
#筛选
colmn = ["colmn1", "colmn2", "colmn3"]
cellContent = ["1000", "2000", "3000"]
#首先确保列表具有相同的大小
if( len(colmn) == len(cellContent)):
curIdx = 0
for curColmnName in colmn:
df_columns= df_columns.loc[df_columns [curColmnName]==cellContent[curIdx]]
curIdx += 1
Thank you again!
再次感谢!
英文:
In Python I have to build a (long) if statement dynamically.
How can I do this?
I tried the following test code to store the necessary if-statement within a string with the function "buildFilterCondition".
But this doesn´t work...
Any ideas? What is going wrong?
Thank you very much.
Input = [1,2,3,4,5,6,7]
Filter = [4,7]
FilterCondition = ""
def buildFilterCondition():
global FilterCondition
for f in Filter:
FilterCondition = FilterCondition + "(x==" + str(f) +") | "
#remove the last "| " sign
FilterCondition = FilterCondition[:-2]
print("Current Filter: " + FilterCondition)
buildFilterCondition()
for x in Input:
if( FilterCondition ):
print(x)
With my Function buildFilterCondition() I want to reach the following situation, because the function generates the string "(x==4) | (x==7)", but this doesn´t work:
for x in Input:
if( (x==4) | (x==7) ):
print(x)
The output, the result should be 4,7 (--> filtered)
The background of my question actually had a different intention than to replace an if-statement.
I need a longer multiple condition to select specific columns of a pandas dataframe.
For example:
df2=df.loc[(df['Discount1'] == 1000) & (df['Discount2'] == 2000)]
I wanted to keep the column names and the values (1000, 2000) in 2 separate lists (or dictionary) to make my code a little more "generic".
colmnHeader = ["Discount1", "Discount2"]
filterValue = [1000, 2000]
To "filter" the data frame, I then only need to adjust the lists.
How do I now rewrite the call to the .loc method so that it works for iterating over the lists?
df2=df.loc[(df[colmHeader[0] == [filterValue[0]) & (df[colmHeader[1]] == filterValue[1])]
Unfortunately, my current attempt with the following code does not work because the panda-loc function has not to be called sequentially, but in parallel.
So I need ALL the conditions from the lists directly in the .loc call.
#FILTER
colmn = ["colmn1", "colmn2", "colmn3"]
cellContent = ["1000", "2000", "3000"]
# first make sure, the lists have the same size
if( len(colmn) == len(cellContent)):
curIdx = 0
for curColmnName in colmn:
df_columns= df_columns.loc[df_columns [curColmnName]==cellContent[curIdx]]
curIdx += 1
Thank you again!
答案1
得分: 2
使用 in
运算符
因为简单胜于复杂。
inputs = [1, 2, 3, 4, 5, 6, 7]
value_filter = [4, 7]
for x in inputs:
if x in value_filter:
print(x, end=' ')
# 4 7
英文:
Use in
operator
Because simple if better than complex.
inputs = [1, 2, 3, 4, 5, 6, 7]
value_filter = [4, 7]
for x in inputs:
if x in value_filter:
print(x, end=' ')
# 4 7
答案2
得分: 1
使用operator模块
使用operator模块,您可以在运行时构建一个条件,该条件由操作符和值对的列表组成,用于测试当前值。
import operator
inputs = [1, 2, 3, 4, 5, 6, 7]
# 如果需要,可以动态更改此列表
conditions = [
(operator.ge, 4), # 值需要大于或等于4
(operator.lt, 7), # 值需要小于7
]
for x in inputs:
# 使用all来对所有条件应用and运算符,使用any来应用or运算符
if all(condition(x, value) for condition, value in conditions):
print(x, end=' ')
# 4 5 6
英文:
Use operator module
With the operator module, you can build a condition at runtime with a list of operator and values pairs to test the current value.
import operator
inputs = [1, 2, 3, 4, 5, 6, 7]
# This list can be dynamically changed if you need to
conditions = [
(operator.ge, 4), # value need to be greater or equal to 4
(operator.lt, 7), # value need to be lower than 7
]
for x in inputs:
# all to apply a and operator on all condition, use any for or
if all(condition(x, value) for condition, value in conditions):
print(x, end=' ')
# 4 5 6
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论