gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:14 24 4
gpt4 key购买 nike

我想知道在 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

最佳答案

你可以这样定义:

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

关于python - 如何判断数组中的任何元素是否是给定字符串的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com