简体   繁体   中英

Python : How to filter multiple conditions

I'm trying to filter multiple conditions, but every attempt I do is in vain.

I want to filter every string (ex. Apple, Banana, stage, books etc), but the code just doesn't work as I expected.

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'])

The first condition, " a_list['type1'] == 'A' " was fine.

But the others, " a_list['type2'].= unwanted_type2 " and " a_list['typeb'].= unwanted_type3 " are not working at all. They are not filtering any conditions that I've included in unwanted_type2 and unwanted_type3.

But if I included only one condition, like

if (a_list['type1'] == 'A') and (a_list['type2'] != 'Apple') and (a_list['typeb'] != 'stage'):

then it worked.

What am I doing wrong....?

The logic behind the code is wrong.

If you do a_list['type2'] != unwanted_type2 is like a_list['type2'],={'Apple','Banana','Orange','Melon'} , and you are comparing a value to the entire unwated_type2.

To resolve it, you can use not in in the condition:

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'])

With this method you are looking at

Problem is that you are comparing "string" and list(or iterable)

Try changing code to something below:

unwanted_type2 = ['Apple','Banana','Orange','Melon']

if "Apple" in unwanted_type2:
    print("Condition works!")

if "Raspberry" not in unwanted_type2:
    print("Negative condition works!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM