[英]Can I pass my custom conditional statement for an if loop in python?
Suppose i have a list in python which contains many words.假设我在 python 中有一个列表,其中包含许多单词。 Now I want to print elements in list on basis of a condition, which I have to take from input.
现在我想根据必须从输入中获取的条件打印列表中的元素。 For example, I want all elements which start with 'a' sometimes, or elements which end with 'l'.
例如,我想要所有有时以“a”开头的元素,或者以“l”结尾的元素。
So, I want an applicable method to execute this programme:所以,我想要一个适用的方法来执行这个程序:
a=['','apple','ball','cat']
condition = input()
for i in a :
if condition:
print i
where condition is an expression and I need programme to parse it as a expression instead of string.其中条件是一个表达式,我需要程序将其解析为表达式而不是字符串。
Because you handle strings, you can pass a regex
as an input.因为您处理字符串,所以您可以将
regex
作为输入传递。
It gives you:它为您提供:
if
s and specific conditions for each caseif
和特定条件 Do something like:执行以下操作:
import re
a=['','apple','ball','cat']
regex = re.compile(input())
# filter only the strings in 'a' which match the given pattern
matches = filter(lambda x: regex.match(x), a)
for i in matches:
print(i)
Some examples:一些例子:
input : '^a[az]*$' will match only 'apple'输入:'^a[az]*$' 将仅匹配 'apple'
input : '^[az]*ll' will only match 'ball'输入:'^[az]*ll' 只会匹配 'ball'
It can be done in this way:可以通过以下方式完成:
Create a function which evaluate the condition, and return True or False if it pass or fail.创建一个评估条件的 function,如果通过或失败则返回 True 或 False。
In for loop use call this function with given input.在 for 循环中使用给定输入调用此 function。
Code代码
def condition_function(argument, condition):
# check condition for argument here
# put code to check the condition true ore not
# result is true or false indication argument satisfy the condition
if result is True:
return True
else:
return False
a=['','apple','ball','cat']
condition = input()
for i in a :
if conditions_function(i, condition):
print i
You can use the str.startswith(letter) method:您可以使用 str.startswith(letter) 方法:
a=['','apple','ball','cat']
condition = input()
for i in a :
if i.startswith("a") or i.endswith("i"):
print i
Also, what is "condition" input for?另外,什么是“条件”输入?
Yes, you can.是的你可以。 Use RegEx python library to compile the string and you are good to go.
使用 RegEx python 库编译字符串,一切顺利。
import re
a = ['', 'apple','nike', 'cat']
expression = input()
r = re.compile(expression)
print(expression)
for ain in a:
if(re.findall(r,ain)):
print(ain)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.