Python - 使用嵌套列表时的奇怪IF语句 [英] Python - Weird IF statement while using nested lists

查看:107
本文介绍了Python - 使用嵌套列表时的奇怪IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么没有传递 else 条件。有人能解释一下原因吗?

I don't understand why the else condition is not passed. Can somebody explain why?

#Python 3.4    
list=[]
list_of_list=[]

list.append("Test")
list.append("This")
list_of_list.append(list)
list=[]

print(list_of_list)
print(type(list_of_list))
print(len(list_of_list))

for element in list_of_list:
 if(element[0]=="Test"):
     print("[OK]")
 if(element[0]=="NO"):
     print("[OK]Condition is not verified")
 else:
     print("[OK]Why the condition is verified??")#<--------------------------

输出:

[['Test', 'This']]
<class 'list'>
1
[OK]
[OK]Why the condition is verified??

预期输出:

[['Test', 'This']]
<class 'list'>
1
[OK]

如何修复代码?

推荐答案

如果结构,你有两个

You have two if structures here:

if(element[0]=="Test"): # first block
    print("[OK]")
if(element[0]=="NO"): # second block
    print("[OK]Condition is not verified")
else: # attached to second block
    print("[OK]Why the condition is verified??")

element [0] 等于'Test',它就是这样,所以打印[OK ]。然后检查它是否等于其他东西,当然它不是,所以它然后转到 else 块并打印[OK ]为什么条件被验证?

element[0] is equal to 'Test', which it is, so it prints "[OK]". It then checks whether it's equal to something else, which of course it isn't, so it then goes to the else block and prints "[OK]Why the condition is verified??".

如果你只想打印一件东西,请使用 elif 将它们连接在一起:

If you want to print only one thing, use elif to connect it all together:

if element[0]=="Test": # first block
    print("[OK]")
elif element[0]=="NO": # attached to first block
    print("[OK]Condition is not verified")
else: # still the same block
    print("[OK]Why the condition is verified??")

这篇关于Python - 使用嵌套列表时的奇怪IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆