开发者

Best way to check multiple equalities?

开发者 https://www.devze.com 2023-02-08 13:35 出处:网络
Preferably in Python, What\'s the best way to create a function that checks for multiple equalities? I want the function to return 1 if the input is equal to \"f\", \"fall\", \"F开发者_如何学JAVA\",

Preferably in Python,

What's the best way to create a function that checks for multiple equalities? I want the function to return 1 if the input is equal to "f", "fall", "F开发者_如何学JAVA", "Fall", "fa", etc. and if "fall" is in a dictionary.


Generalizing a bit, it sounds like you have a dictionary of words (commands?) and want to match the first entry that matches partial input, case-insensitive:

D = dict(fall=None,stand=None)
trials = 'f fall F Fall fa foo Foo s ST stan'.split()

def check(t):
    for k in D:
        if k.startswith(t.lower()):
            return k
    return None

for t in trials:
    print '{0:7}{1}'.format(t,check(t))

Output

f      fall
fall   fall
F      fall
Fall   fall
fa     fall
foo    None
Foo    None
s      stand
ST     stand
stan   stand


You can do a pythonic version using filter combined with 'len > 1' ....

input = "fall"
the_list = ["f", "fall", "F", "Fall", "fa"]
your_test = len(filter(lambda x: x == input, the_list)) > 1 \
       and "fall" in your_dictionary
0

精彩评论

暂无评论...
验证码 换一张
取 消