samedi 30 novembre 2019

Is there a pythonic way of referring to the iterators variable names inside of the for loop?

Below is a code snippet:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

...

val = carry
for l in filter(None, [l1, l2]):
    val += l.val
    l = l.next

l1 and l2 are two linked lists. If a list is empty it is set to None such that the loop only processes a linked list if it has not been completely traversed. I want to use the loop to prevent code duplication. The issue is on line four, where upon an iteration of the loop neither l1 or l2 are updated with the next node of the list but l is instead. Does anyone know of any nice patterns to fix this issue? Apologies if this question has been asked before but I do not know of the correct terminologies to search for an answer. Perhaps defining a separate function or an anonymous function would be the best way to go?

Aucun commentaire:

Enregistrer un commentaire