python - 通过布尔 if-elif-else 条件循环嵌套列表
问题描述
我计划分析反对党、联盟或跨议员法案的比例的立法。
我写了两个简单的检查any()
来检查是否在列出反对党和联盟党的名单中找到了共同起草法案的政党的内部名单。
coalition = ['CD&V', 'N-VA', 'Open Vld']
opposition = ['sp.a', 'Groen', 'Vlaams Belang', 'PVDA']
parties = [['Groen', 'sp.a'], ['CD&V', 'N-VA'], ['sp.a', 'CD&V']] # test cases, one for each outcome
check_op = any(party in parties for party in opposition)
check_co = any(party in parties for party in coalition)
然后我遍历列表列表并使用执行检查if elif else
for p in parties:
if check_op is True and check_co is False:
print("This is an opposition bill")
elif check_co is True and check_op is False:
print("This is a coalition bill")
elif check_co is True and check_op is True:
print("This is a cross bench bill")
else:
print('none')
结果总是:
none
none
none
而我期望:
This is an opposition bill
This is a coalition bill
This is a cross bench bill
当我尝试仅使用一个各方列表而不是遍历嵌套列表来遍历条件时,结果会正确显示...
我做错了什么,我怎样才能让 for 循环通过条件并获得正确的结果。谢谢你。
解决方案
您的代码的问题是您正在评估string
. List of Strings
尝试以下代码:
coalition = ['CD&V', 'N-VA', 'Open Vld']
opposition = ['sp.a', 'Groen', 'Vlaams Belang', 'PVDA']
parties = [['Groen', 'sp.a'], ['CD&V', 'N-VA'], ['sp.a', 'CD&V']] # test cases, one for each outcome
for p in parties:
check_op,check_co = False,False
for member in p:
if member in opposition:
check_op = True
elif member in coalition:
check_co = True
if check_op and not check_co:
print("This is an opposition bill")
elif check_co and not check_op:
print("This is a coalition bill")
elif check_co and check_op:
print("This is a cross bench bill")
else:
print('none')
输出:
This is an opposition bill
This is a coalition bill
This is a cross bench bill
推荐阅读
- angular - 对 Azure Blob 存储帐户中托管的 Angular 应用程序的 URLRewrite 支持
- css - 为什么固定到顶部的导航栏(位置:固定)需要宽度属性?
- windows - 使用连字符名称批量重命名多个文件
- bash - 如何读取 shell 脚本中的两行(在单次迭代中第 1 行、第 2 行 - 下一次迭代应该采用第 2 行、第 3 行……依此类推)
- deep-learning - 训练 MTCNN 进行人脸检测
- arrays - 从 Google 表格中的单个范围拆分多个范围
- spring-boot - 如何设计在springboot中接受JSON数组作为输入的post api?
- heroku - Heroku烧瓶webapp部署中的requirements.txt vs Pipfile?
- sql - 将列值分隔为行值
- dart - 如何使用 dart 截取特定应用程序?