1 python for-loop if-statement
请看下面的代码:
for l in range(len(cosine_scores)):
for s in range(len(skill_index)):
if l!=skill_index[s] :
if cosine_scores[l][skill_index[s]]>=0.80:
print(l)
Run Code Online (Sandbox Code Playgroud)
如何在s打印之前以 if 条件满足所有人的方式重写此代码l?
例如,如果我有
my_list=[[10,8],[8,,0,1,2,7],[6,15,8]]
for i in my_list:
for j in i:
if j>5: # I don't know what I should add here to say if this condition is true for all j in i.
print(i)
Run Code Online (Sandbox Code Playgroud)
正确的输出应该是[10,8]和[6,15,8]。
all方法如果可迭代的所有元素都为 true(或者可迭代为空),则返回Trueall
for i in my_list:
if all(j > 5 for j in i):
print(i)
Run Code Online (Sandbox Code Playgroud)
for/else该else块仅break在迭代期间未使用时被调用
for i in my_list:
for j in i:
if not j > 5:
break
else:
print(i)
Run Code Online (Sandbox Code Playgroud)
for l in range(len(cosine_scores)):
for s in range(len(skill_index)):
if not (l != skill_index[s] and cosine_scores[l][skill_index[s]] >= 0.80):
break
else:
print(l)
---
for l in range(len(cosine_scores)):
if all(l != skill and cosine_scores[l][skill] >= 0.80 for skill in skill_index):
print(l)
Run Code Online (Sandbox Code Playgroud)