Home > Back-end >  Is there a better way to get an int result out of list comprehension than try except (when None or e
Is there a better way to get an int result out of list comprehension than try except (when None or e

Time:05-18

Editing for clarity:

I am using list comprehension to get out single fields from lists of data. I only want the integer value from the list comprehenions, but list comprehension gives me lists of lists. So for example, I'd pass in an ordered list of items, and get back an int quantity of used items, except it won't give me a list of ints. it will give me a list like this: [[1], [2], [5], [60], [0], [], [], [4]] (I will have None values in here as well at times since I'm pulling from a database with missing values, which may be a problem in itself. But that is not the focus of this question. I'd like to know if there are ways of getting the values without running into index errors.

resource['new_item'] = [item['used_qty'] for item in items if item['item_id'] == resource['item_id']]
    try:
        resource['new_item'] = resource['new_item'][0]
    except IndexError:
        resource['new_item'] = 0

Getting out single ints from list comprehension seems to be more difficult than it should be when there is the potential for None or empty arrays being involved.

One way I use when I have a list of single int lists, like this is:

a = [[1], [2], [3], [4], [5]]
a = sum(a, [])
print(a)
>>> [1, 2, 3, 4, 5]

or

a[0]

Or I use:

a = [letter for letter in letters if letter == something].pop()

or

a = [letter for letter in letters if letter == something][0]

But all of these break if there is possibly a None or an empty array returned, which I am dealing with a lot in what I am working on now. Please share some good ways to get at the juicy int inside the list that are better than try, except.

CodePudding user response:

you can do something like

resource['new_item'] = 0
# just update first matching result
for item in items:
    if item['item_id']==resourc['item_id']:
        resource['new_item'] = item['used_qty']
        break

CodePudding user response:

I'm still not sure if I entirely understand the question, but you could try with or switch in python, which will evaluate second part after or if the first part is falsy, such as an empty list or None value as mentioned.

For example:

resource['new_item'] = [item['used_qty'] or [0] for item in items if item['item_id'] == resource['item_id']]

# defaults to `0` if contains falsy value
resource['new_item'] = resource['new_item'][0]
  • Related