[英]Python : How to filter multiple conditions
我正在尝试过滤多个条件,但我所做的每一次尝试都是徒劳的。
我想过滤每个字符串(例如 Apple、Banana、stage、books 等),但代码并没有像我预期的那样工作。
B = []
wanted_type1 = 'A'
unwanted_type2 = {'Apple','Banana','Orange','Melon'}
unwanted_type3 = {'stage','books','films','music'}
al = urllib.request.urlopen(URL).read()
als = json.loads(al)
a_list = als['response']['results']
for list in a_list:
if (a_list['type1'] == 'A') and (a_list['type2'] != unwanted_type2) and (a_list['typeb'] != unwanted_type3):
B.append(list['type4'])
第一个条件“a_list['type1'] == 'A'”很好。
但是其他的“ a_list['type2'].= Wanted_type2 ”和“ a_list['typeb'].= Wanted_type3 ”根本不起作用。 他们没有过滤我在不需要的类型 2 和不需要的类型 3 中包含的任何条件。
但如果我只包括一个条件,比如
if (a_list['type1'] == 'A') and (a_list['type2'] != 'Apple') and (a_list['typeb'] != 'stage'):
然后它起作用了。
我究竟做错了什么....?
代码背后的逻辑是错误的。
如果您这样做a_list['type2'] != unwanted_type2
Wanted_type2 就像a_list['type2'],={'Apple','Banana','Orange','Melon'}
,并且您将一个值与整个 unwated_type2 进行比较.
要解决它,您可以在条件中使用not in
:
B = []
wanted_type1 = 'A'
unwanted_type2 = {'Apple','Banana','Orange','Melon'}
unwanted_type3 = {'stage','books','films','music'}
a_list = some_variable['response']['results']
for list in a_list:
if (a_list['type1'] == 'A') and (a_list['type2'] not in unwanted_type2) and (a_list['typeb'] not in unwanted_type3):
B.append(list['type4'])
使用这种方法,您正在查看
问题是您正在比较“字符串”和列表(或可迭代)
尝试将代码更改为以下内容:
unwanted_type2 = ['Apple','Banana','Orange','Melon']
if "Apple" in unwanted_type2:
print("Condition works!")
if "Raspberry" not in unwanted_type2:
print("Negative condition works!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.