简体   繁体   中英

Nested If Statement not Evaluating as expected

I have two lists that I am trying to compare:

a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}]

b = ['oranges', 'bananas', 'apples']

I just want to see if any element of a's name value can be matched to b and if so append the bushel value to an empty list. Like so:

f = []
a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}]
b = ['oranges', 'bananas', 'apples']
for item in a:
    if item['name'].lower() in b:
        f.append(item['bushels'])
    print(f)

f is returning [], the problem seems to be in the if statement. Not sure but seems like I might be attempting the wrong operation there?

item['name'].lower() in b won't work as you intend because the strings don't match exactly. For instance 'ORANGES_060222' isn't the same as 'orange' (even with lower ).

Instead you can remove all non alphabet characters using isalpha

item_name = ''.join([c for c in item['name'].lower() if c.isalpha()])
if item_name in b:
    ...

You are probably looking for something like this -

f = []
a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}]
b = ['oranges', 'bananas', 'apples']
for item in a:
    for b_items in b:
        if b_items in item['name'].lower():
            f.append(item['bushels'])
            
print(f)

Output:

[5, 3]

What this does is checks if any of b exists in a. In your code, you were doing item['name'].lower() which returns ORANGES_060222 which doesn't exists in b. What you probably wanted to check if orange part from a[0] existed in b.


You can also do it as -

f = []
a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}]
b = ['oranges', 'bananas', 'apples']
for item in a:
    if item['name'].lower().split('_')[0] in b:
        f.append(item['bushels'])
        
print(f)

Output:

[5, 3]

This method can be used if every element in a occurs in the format - NAME_NUMBER . So, item['name'].lower().split('_')[0] will only return the name part ( oranges in the first case ) and then you can check if it exists in b to get the desired results.

Hope this helps !

You should do the reverse:

f = []
a = [{'name': 'ORANGES_060222', 'bushels': 5}, {'name': 'BANANAS_062620', 'bushels': 3}]
b = ['oranges', 'bananas', 'apples']
for item in a:
    for x in b:
        if b in item['name'].lower():
            f.append(item['bushels'])
            break
    print(f)

You can simply use this nested list comprehension:

f = [item['bushels'] for item in a for d in b if d in item['name'].lower()]

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