Home > Mobile >  How to get for loop into list comprehension?
How to get for loop into list comprehension?

Time:02-02

My for loop goes as follows:

Object_id_lst = []

for id_tic in ticket_df['ID']:
    get_object_id = api_client.crm.tickets.associations_api.get_all(ticket_id=id_tic, to_object_type='contacts')
    if len(get_object_id.results) > 0:
        Object_id_lst.append(get_object_id.results[0].to_object_id)
    else:
        object_id = 0
        Object_id_lst.append(object_id)

I wanted to see if there was a way to get this into a list comprehension for faster computing time.

CodePudding user response:

It's not pretty, but you can do it by using the walrus operator to assign get_object_id inside the list comprehension, so you can test its length and also use it in the value part of the comprehension.

Object_id_list = [
    get_object_id.results[0].to_object_id 
        if len((get_object_id := api_client.crm.tickets.associations_api.get_all(ticket_id=id_tic, to_object_type='contacts')).results) > 0 
        else 0
    for id_tic in ticket_df['ID']]

More realistically, I would move all that conditional code into a function, and map that.

def object_id(id_tic):
    get_object_id = api_client.crm.tickets.associations_api.get_all(ticket_id=id_tic, to_object_type='contacts')
    if len(get_object_id.results) > 0:
        return get_object_id.results[0].to_object_id
    else:
        return 0

Object_id_list = list(map(object_id, ticket_df['ID']))

CodePudding user response:

Object_id_list = [api_client.crm.tickets.associations_api.get_all(ticket_id=id_tic, to_object_type='contacts').results[0].to_object_id 
                  if len(api_client.crm.tickets.associations_api.get_all(ticket_id=id_tic, to_object_type='contacts')) > 0
                  else 0
                  for id_tic in ticket_df['ID']

CodePudding user response:

I don't think making it a list comprehension will help much, other optimizations might help more. I did both:

Object_id_lst = [
    results[0].to_object_id if results else 0
    for get_all in [api_client.crm.tickets.associations_api.get_all]
    for id_tic in ticket_df['ID']
    for results in [get_all(ticket_id=id_tic, to_object_type='contacts').results]
]

My optimizations (besides making it a comprehension):

  • Fetching the get_all function only once instead of every time.
  • Fetching .results only once instead of twice.
  • Checking truth of results instead of calling len on it, comparing with 0, and checking the truth of the comparison result.

Another alternative (should be in a function, not global, so you get faster variables):

Object_id_lst = []
append = Object_id_lst.append
get_all = api_client.crm.tickets.associations_api.get_all
for id_tic in ticket_df['ID']:
    for result in get_all(ticket_id=id_tic, to_object_type='contacts').results:
        append(result.to_object_id)
        break
    else:
        append(0)
  • Related