-3

I have the loop like this

for a in list1:
     for b in list2:
         for c in list3:
             print "Hello"

Without using any if else statement. i want that if there are elements in all list then it should repeat as normal but if the list is empty then for loop should behave like its don't exist and runs the code below it once

like if list3 is empty and list2 contains 2 elements and list1 has one element then i should see hello 2 times

4

1 回答 1

8
for a in list1 or [None]:
     for b in list2 or [None]:
         for c in list3 or [None]:
             print "Hello"

The None in [None] can be replaced by any other single object.

This way the empty list will be replaced by a list with one element and the loop will proceed once.

Other way (if the variables a, b and c are not important) would be:

for i in xrange(max(len(list1), 1) * max(len(list2), 1) * max(len(list2), 1))):
    print 'Hello'

UPDATE

Your idea of using my code without adapting it correctly:

for m,n in zip(l1,l2) or [None]:

can be corrected using:

for m,n in zip(l1 or [None], l2 or [None]):

or

for m,n in zip(l1, l2) or [[None, None]]:
于 2013-04-26T07:44:32.850 回答