首页 > 解决方案 > 当条件满足时,我试图降低分数

问题描述

当条件满足时,我试图降低分数。但未能如愿。

data = ['A','B']
Score = 10
words = [ 'C', 'D']

for i in data:
     if i in words:
          do nothing
     else:
         reduce score by 2

在这里,当 A 和 B 都不存在时,我希望我的分数只减少一次,而不是两次。

Expected output : 8

代码 :

index = []
for i in data:
     if i in words:
          do nothing
     else:
         index.append(something)

if len(index) > 1:
       reduce score by 2

这就是我写的,但是有没有办法让这变得不那么复杂??

标签: pythonpandasloopsdataframe

解决方案


data = ['A','B']
score = 10
words = [ 'C', 'D']

data_not_found_list = [False for dt in data if dt not in words]

if not any(data_not_found_list):
    score -= 2

print(score)

输出 : 8

我在这里使用了 any() 方法。您可以阅读如何获得一个想法 - https://realpython.com/any-python/


推荐阅读