[英]Find if at least one string of a list of strings hasn't a character (python)
I want to check if, among the elements of a list of strings, at least one of the element has not a "-" in it. 我想检查一下,在一个字符串列表的元素中,至少一个元素中是否没有“-”。 I tried :
我试过了 :
print not any("-" in elem for elem in my_list)
With: 带有:
my_list = ['gta', '---', '---', 'gta']
it should return True
and with : 它应该返回
True
并带有:
my_list = ['gt-', 'ac-', 'ca-', 'gt-']
It should return False
. 它应该返回
False
。 It's always False
for now, is there a one-line command to do that ? 目前始终为
False
,是否有单行命令来执行此操作? I could choose the easy way and make my code on several lines, but I want to practice these kinds of commands :). 我可以选择简单的方法,并在多行代码中编写代码,但是我想练习这些命令:)。
如评论中所述,由于not any
变成all not
您不需要使用not all
。
You can use re.findall
to check if the entire string in the list is composed of "-"
: 您可以使用
re.findall
检查列表中的整个字符串是否由"-"
组成:
import re
def check_string(s):
return any(re.findall('^-+$', i) for i in s)
lists = [[['gta', '---', '---', 'gta'], True], [['gt-', 'ac-', 'ca-', 'gt-'], False]]
for a, b in lists:
assert check_string(a) == b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.