def merge(l1,l2):
i=0;
while((l1[i]!=none)||(l2[i]!=none)):
S开发者_开发技巧yntaxError: invalid syntax being a newbie i can't figure out whats wrong with the abouve code.
Replace ||
with or
, make None
upper-case (and lose the semi-colon):
def merge(l1, l2):
i = 0
while l1[i] != None or l2[i] != None:
pass
(As you can see, the parentheses were also redundant.)
Furthermore, != None
can be changed to is not None
:
while l1[i] is not None or l2[i] is not None:
(Thanks to @SilentGhost for pointing that out.)
Even more Pythonic would be something like this (since it looks like you are iterating over both lists until one hits a 'None' value):
for l1val,l2val in zip(l1,l2):
if l1val is None or l2val is None:
break
... rest of while loop goes here, using l1val and l2val
instead of l1[i] and l2[i]
In fact, that None sentinel looks a little weird. If this is something you tacked onto the end so you know when you are at the end of the list, then don't bother - just use Python's own iteration features (for loops automatically stop at the end of the list they are iterating over.*)
for l1val,l2val in zip(l1,l2):
... body of while loop goes here, using l1val and l2val
instead of l1[i] and l2[i]
*-They don't really stop automatically - the list iterator raises the exception StopIteration, which is caught by the for loop as a signal to stop looping.
My crystal ball is getting fuzzier, but there is one more clue, in your method name 'merge'. Let's say merge takes two lists, and each list is a list of integers, and by 'merge', you mean return a new list of the sums of the respective values in l1 and l2. Here is what merge looks like with a for loop:
def merge(l1, l2):
retl = []
for v1,v2 in zip(l1, l2):
retl.append(v1+v2)
return retl
As a newbie, you should learn about and get very comfortable with a concept called "list comprehensions". Using a list comprehension, you can simplify your merge method to the simple:
def merge(l1, l2):
return [v1+v2 for v1,v2 in zip(l1, l2)]
This is equivalent to the previous function - please study these and see how that works. And finally, in a flashing moment of Python's duck typing, run merge as-is, but this time passing it a list of lists instead of a list of ints. (Left as an exercise for the OP.)
精彩评论