[英]How to check if a String contains at least 2 elements from a list
For eg the variable is a boolean: char_check = False例如,变量是 boolean:char_check = False
For eg the string is "python i$ cool_123"(the string can vary depending on the input)例如,字符串是“python i$ cool_123”(字符串可能因输入而异)
And the list is "[$, &, #, @,1,2,3]列表是“[$, &, #, @,1,2,3]
If the string contains at least two elements from the list then char_check = True.如果字符串至少包含列表中的两个元素,则 char_check = True。 But i only know how to check if a string contains one item from a list using the any() function, not 2 or multiple items in a list.
但我只知道如何使用 any() function 检查字符串是否包含列表中的一项,而不是列表中的 2 项或多项。
Any help or solutions will Be appreciated thank you任何帮助或解决方案将不胜感激谢谢
I tried using the any(function) but it only checks if a string contains at least one item not 2 or more我尝试使用 any(function) 但它只检查字符串是否包含至少一项而不是 2 项或更多项
Tl:dr A string inputted should have at least two elements from a list Tl:dr 输入的字符串应至少包含列表中的两个元素
This is a possible solution:这是一个可能的解决方案:
def check_chars(s, lst):
return len(set(s) & set(lst)) >= 2
Examples:例子:
>>> check_chars("abc", ["a", "d"])
False
>>> check_chars("abc", ["a", "c"])
True
Another option:另外的选择:
def check_chars(s, lst):
it = iter(s)
return any(c in lst for c in it) and any(c in lst for c in it)
def func(string,lst):
count=0
for i in string:
if i in lst:
count+=1
if count>=2:
return True
else:
return False
lst=['$', '&', '#', '@', '1', '2', '3']
string=input("Enter the sting:")
print(func(string,lst))
Hope it helped..希望它有所帮助..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.