【问题标题】:How to tell if any element in an array is a substring of a given string?如何判断数组中的任何元素是否是给定字符串的子字符串?
【发布时间】:2012-12-06 02:14:42
【问题描述】:

我想知道在 Python 中是否有更有效的方法来执行此操作。 I found a good solution in Ruby 但它似乎相当具体。

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

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

【问题讨论】:

    标签: python string substring


    【解决方案1】:

    你可以这样定义:

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

    【讨论】:

      【解决方案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的东西。

      【讨论】:

      • 我真的很喜欢你的第二个建议,我也许可以把它放在某个地方。另外,我实际上只是想出了一个与您类似的解决方案(我只是将any_in_string 代码拉到一个文字 for 循环中,而不是调用一个函数)。
      猜你喜欢
      • 1970-01-01
      • 2017-10-15
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      相关资源
      最近更新 更多