#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    26
    Rep Power
    0

    Can I express this any better


    Code:
    for task in tasks:
            if task.Role=='BDTR':
                print task.Decision
            else:
                print 'False TASK'
    Assuming the task object has attributes Role and Decision
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,696
    Rep Power
    480
    If your python is recent enough,
    Code:
    for task in tasks:
        print(task.Decision if task.Role=='BDTR' else 'False TASK')
    and if not,
    Code:
    for task in tasks:
        print(('False TASK', task.Decision)[task.Role=='BDTR'])
    Either way, and there are other ways, print was duplicate code.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    26
    Rep Power
    0
    Originally Posted by b49P23TIvg
    If your python is recent enough,
    Code:
    for task in tasks:
        print(task.Decision if task.Role=='BDTR' else 'False TASK')
    and if not,
    Code:
    for task in tasks:
        print(('False TASK', task.Decision)[task.Role=='BDTR'])
    Either way, and there are other ways, print was duplicate code.
    Thanks.

    is there such a thing as First() i.e get the first element that meets a criteria in a list, i.e something like any() or all() that returns the first element that meets a cruiteria instead of a boolean

    I'm currently writing this. I'm wondering if there a better way
    Code:
    currenttask  = list(task for task in tasks if task.TaskId()==taskId)[0]
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,696
    Rep Power
    480
    I'd go with
    Code:
    for task in tasks:
        if task.TaskId() == taskId:
            currenttask = task
            break
    else:
        currenttask = None
    to avoid checking the entire list. Every time I've timed list comprehensions they run more slowly than explicit loops. Comprehensions are kinda fun to write though.

    Comments on this post

    • Dietrich agrees : makes sense
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo