简体   繁体   中英

How to iterate through discontiguous for loop in python

I'm writing a scale script where I need to iterate through discontiguous list using for loops.

My requirement is I have two sets of vlans say:

  1. no_of_l2_vlans , start_l2_vlan -- This refers to one set and inside each element I do certain operation.
  2. no_of_l3_vlans, start_l3_vlan -- This refers to another set and I perform same set of operation as I did for the previous iteration,

I have accomplished that using two for loops for each set linearly but just wondering if there is an effective way of doing it?

 for i in range(l2_vlan_start,l2_vlan_start+no_of_l2_vlans):
     <some set of operations>

 for i in range(l3_vlan_start,l3_vlan_start+no_of_l3_vlans):
     <same set of operations>

Since the operations are same can I combine these two for loops into a single one?

Please advise .

While I prefer @0x5453's answer-as-a-comment, here's something a bit more spcialized to your problem & shows how the sausage is made:

def mychain(spans):
    for start, no in spans:
        for i in range( start, start+no ):
            yield i

for x in mychain(((l2_vlan_start,no_of_l2_vlans),(l3_vlan_start,no_of_l3_vlans))):
    print(x)

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