首页 > 解决方案 > 通过布尔 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 循环通过条件并获得正确的结果。谢谢你。

标签: pythonloopsif-statementboolean

解决方案


您的代码的问题是您正在评估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

推荐阅读