我有四个列表,我想检查list_1中的一个单词以及list_2中的单词是否与另一个字符串(但该子字符串仍然存在)相同,对于所有四个列表,如果该子字符串存在于所有四个列表中那么打印。
假设我有这四个列表:
a=["1","2","45","32","76"]
b=["5","8","345","32789","43"]
c=["362145","9932643","653"]
d=["194532","5423256","76"]
所以我想在列表a和列表b中匹配45
,32
,因为34
5包含34但它还包含45 3 45
和{{ 1}} 789包含32,列表c包含3621 32
和99 [45]
643包含32,因此在列表d 19 [32]
32包含45和542 [45]
56包含32因此,如果子串(示例45)在所有4列表中,则打印。
我尝试使用“in”方法,但是这不起作用然后我尝试使用set()也不起作用,我该怎么办?
P.S:有什么方法没有循环遍历列表?因为这个模块是一个大型程序的子模块,并且该程序已经包含很多循环,如果可能的话没有循环,否则所有建议都欢迎:)
答案 0 :(得分:0)
使用any("45" in s for s in a)
来检查该号码是否在列表a中,依此类推。如果找到它,则返回True
。
编辑:这是一个例子。
check = input("What number are you looking for?")
if any(check in s for s in a):
if any(check in s for s in b):
if any(check in s for s in c):
if any(check in s for s in d):
print("something")
答案 1 :(得分:0)
>>> a = ["1", "2", "45", "32", "76"]
>>> b = ["5", "8", "345", "32789", "43"]
>>> c = ["362145", "9932643", "653"]
>>> d = ["194532", "5423256", "76"]
>>> x, y = "45", "32"
>>> all(any(x in i for i in lst) and any(y in i for i in lst) for lst in [a, b, c, d])
True
答案 2 :(得分:0)
就像你描述的那样,它不可能避免循环,但你可以使用理解列表。
例如:
a = ["1","2","45","32","76"]
b = ["5","8","345","32789","43"]
c = ["362145","9932643","653"]
d = ["194532","5423256","76"]
result = []
for x in a:
if (any(x in s for s in b) and
any(x in s for s in c) and
any(x in s for s in d)):
result.append(x)
每个any
使用一个iterable来检查项目 x 是否存在于列表 b , c 的任何字符串中 d
可以使用列表理解来重写此构造:
result = [x for x in a
if (any(x in s for s in b) and
any(x in s for s in c) and
any(x in s for s in d))]
print(result)
你得到:
['2', '45', '32']