Python 类对象出现在for循环的if和else语句下为什么?
为什么带有option=“first”的类对象出现在列表Python 类对象出现在for循环的if和else语句下为什么?,python,class,for-loop,if-statement,Python,Class,For Loop,If Statement,为什么带有option=“first”的类对象出现在列表btest和列表ctest中 我在一段较大的代码中遇到了这个问题,所以我编写了这段较小的代码,以便更好地理解if/else语句如何在类对象列表的for循环中工作。但我还是不明白 class test: def __init__(self,option,place): self.option=option self.place=place def __repr__(self): retu
btest
和列表ctest
中
我在一段较大的代码中遇到了这个问题,所以我编写了这段较小的代码,以便更好地理解if/else语句如何在类对象列表的for循环中工作。但我还是不明白
class test:
def __init__(self,option,place):
self.option=option
self.place=place
def __repr__(self):
return("option:"+self.option+"\npalce:"+self.place)
optionlist=["first","second","thrid","fourth"]
placelist=["switzerland","germany","thailand","italy"]
testlist=[]
item=0
while item <len(optionlist):
testl=test(optionlist[item],placelist[item])
testlist.append(testl)
item+=1
btest=[]
ctest=[]
for x in testlist:
if x.option=="first":
btest.append(x)
print("here")
if x.option=="second":
print("here2")
# If I delete this 2nd if statement the ctest list
# doesn't contain a object with option="first", but if I
# leave it it does. Why?
else:
ctest.append(x)
print("no")
print("btest:",btest)
print("ctest:",ctest)
这也是我所期望的,但是如果我让它用第二条if语句运行,为什么它会给出以下输出:
here
no
here2
no
no
btest: [option:first
palce:switzerland]
ctest: [option:first
palce:switzerland, option:thrid
palce:thailand, option:fourth
palce:italy]
因为它是两个不同的
if
语句。
看起来您需要使用if/elif/else
:
if x.option=="first":
btest.append(x)
print("here")
elif x.option=="second":
print("here2")
# If I delete this 2nd if statement the ctest list
# doesn't contain a object with option="first", but if I
# leave it it does. Why?
else:
ctest.append(x)
print("no")
因为你把它编码成这样:
if x.option=="first":
btest.append(x) # when x.option == "first" add to btest
print("here")
if x.option=="second":
print("here2")
else:
ctest.append(x) # when x.option NOT "second" add to ctest
print("no") # x.option == "first" is NOT second - so added
您可以将其更改为if:elif:else:。。。然后,second
将永远不会添加到任何内容中,因为它只打印s
if x.option=="first":
btest.append(x) # when x.option == "first" add to btest
print("here")
if x.option=="second":
print("here2")
else:
ctest.append(x) # when x.option NOT "second" add to ctest
print("no") # x.option == "first" is NOT second - so added