如何判断数组中的任何元素是否是给定字符串的子字符串?

时间:2012-12-06 02:14:43

标签: python string substring

我想知道在Python中是否有更有效的方法来做到这一点。 I found a good solution in Ruby但似乎相当具体。

基本上,我从API获取天气状况数据,并希望将他们的许多细微差别条件标准化为7,我可以轻松处理它们。

def standardize_weather_conditions(s):
    clear_chars = ['clear', 'sunny']
    clouds_chars = ['cloudy', 'overcast', 'fog']
    storm_chars = ['thunder']
    freezing_chars = ['ice', 'sleet', 'freezing rain', 'freezing drizzle']
    snow_chars = ['snow', 'blizzard']
    rain_chars = ['rain', 'drizzle', 'mist']

    if any_in_string(s, clear_chars):
        conditions = 'clear'
    elif any_in_string(s, clouds_chars):
        conditions = 'clouds'
    elif any_in_string(s, storm_chars):
        conditions = 'storm'
    elif any_in_string(s, freezing_chars):
        conditions = 'freezing'
    elif any_in_string(s, snow_chars):
        conditions = 'snow'
    elif any_in_string(s, wet_chars):
        conditions = 'wet'
    else:
        conditions = 'other'
    return conditions

def any_in_string(s, array):
    for e in array:
        if e in s:
            return True
    return False

2 个答案:

答案 0 :(得分:2)

您可以这样定义:

def any_in_string(s, lst):
    return any(word in s for word in lst)

答案 1 :(得分:2)

通过执行any_in_string

,可以将

return any([x in s for x in array])打造成一行

然后你可以制作一个字典,将你的描述映射到你的搜索词列表:

all_chars = {'clear':clear_chars, \
             'clouds':clouds_chars, \
             'storm':storm_chars, \
             'freezing':freezing_chars, \
             'snow':snow_chars, \
             'wet':rain_chars }

for key in all_chars.keys():
     if any_in_string(s, all_chars[keys]):
         return key

return 'other'

这有助于避免'意大利面条代码'if-else阻止你。

如果您想要更加花哨,可以将上面的for循环更改为:

conditions = [x for x in all_chars.keys() if any_in_string(s, all_chars[x])]
conditions = ' and '.join(conditions)
return conditions

通过这种方式,您可以获得类似cloudy and wet的内容。