我想仅在现有字符串列表中不包含该字符串(甚至作为子字符串)的情况下,才将字符串添加到字符串列表中。不区分大小写。
我可以将它作为一个函数来使用,但是它不像我想的那样是Pythonic的-我感觉这可能是使用列表推导的单行代码,但是我还没有弄清楚怎么做。
这是我所做的工作:
def append_if_new(string, strings):
for s in strings:
if string.lower() in s.lower():
return(strings)
strings.append(string)
return strings
没有函数,如何用Python做到这一点?
只需内置any
功能即可:
if not any(search_str.lower() in s.lower() for s in strings):
strings.append(search_str)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句