Thread: python list comp

Results 1 to 2 of 2
  1. #1 python list comp 
    Respected Member


    Join Date
    Jul 2015
    Posts
    781
    Thanks given
    206
    Thanks received
    394
    Rep Power
    524
    Trying to shorten the following:

    Code:
    # for each edge, attempt to ping it up to 5 times
    for edge in edges:
        for count in range(5):
            ping = os.system('ping -c 1 ' + edge['defaultNat'])
            if ping == 0:
                break
            elif count > 3:
                failed_edges.append(edge)
    to a one liner (ala list comprehension). I was thinking something along the lines of:

    Code:
    [os.system('ping -c 1 ' + edge['defaultNat']) for edge in edges for _ in range(5)]
    but I'm stuck on referencing the output of the system call and short-circuiting if it's successful. (any()?)

    Any suggestions?
    Reply With Quote  
     

  2. #2  
    Extreme Donator

    nbness2's Avatar
    Join Date
    Aug 2011
    Posts
    692
    Thanks given
    274
    Thanks received
    139
    Rep Power
    430
    i guess the easiest way would be to define a function that raises StopIteration and call it when you get your desired "short circuit" output (assuming its 0).

    Code:
    def zero_ping:
        raise StopIteration()
    [ [ zero_ping() if os.system('ping -c 1 ' + edge['defaultNat']) == 0 else edge for count in range(5) ] for edge in edges ]
    this is really hacky and you should stick with loops rather than trying to shove everything in a list comp when doing something like this that needs breaks. list comps have negligible speedup and complicate things much more.
    KT/JAVA - NBX 637 - HERE!
    KT - Drop table 4: Flexible, Powerful - HERE!
    KT - Command: Simplify writing commands - HERE
    KT - NbUtil: Make your kotlin easier - HERE
    KT - Hopping Islands: From Java to Kotlin - P1 - P2 - P3 - P4 - P5
    Reply With Quote  
     


Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Server & Client Download list
    By Link in forum Downloads
    Replies: 64
    Last Post: 01-28-2012, 08:32 PM
  2. List Of All GFX Tutorials.
    By Karlis in forum Tutorials
    Replies: 16
    Last Post: 02-01-2009, 07:18 AM
  3. Replies: 19
    Last Post: 01-10-2008, 10:15 PM
  4. Model List
    By Zachera in forum RS2 Client
    Replies: 1
    Last Post: 05-01-2007, 02:40 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •