python `list` and `for` return different results -
why list
, for
study different result if utilize them on values generated function?
from collections import deque def neighbours(comp0, cand0): comp = deque([i in comp0]) cand = deque([i in cand0]) in range(len(cand)): elem = cand.popleft() comp.append(elem) yield comp, cand comp.pop() cand.append(elem) homecoming >>> n = neighbours([2], [1,4,5]) >>> list(n) [(deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5]))] >>> n = neighbours([2], [1,4,5]) >>> in n: ... print(i) ... (deque([2, 1]), deque([4, 5])) (deque([2, 4]), deque([5, 1])) (deque([2, 5]), deque([1, 4])) >>>
your objects modified iterate; printing intermediate results when using for
, final results when printing list.
if append results list first, same results list()
output again:
>>> n = neighbours([2], [1,4,5]) >>> res = [] >>> in n: ... print(i) ... res.append(i) ... (deque([2, 1]), deque([4, 5])) (deque([2, 4]), deque([5, 1])) (deque([2, 5]), deque([1, 4])) >>> res [(deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5])), (deque([2]), deque([1, 4, 5]))]
each element in res
tuple same 2 deque objects:
>>> res[0][0] res[1][0] res[2][0] true >>> res[0][1] res[1][1] res[2][1] true
you yield list()
copies of each deque
instead, , create new objects:
>>> def neighbours(comp0, cand0): ... comp = deque([i in comp0]) ... cand = deque([i in cand0]) ... in range(len(cand)): ... elem = cand.popleft() ... comp.append(elem) ... yield list(comp), list(cand) ... comp.pop() ... cand.append(elem) ... >>> n = neighbours([2], [1,4,5]) >>> res = [] >>> in n: ... print(i) ... res.append(i) ... ([2, 1], [4, 5]) ([2, 4], [5, 1]) ([2, 5], [1, 4]) >>> res [([2, 1], [4, 5]), ([2, 4], [5, 1]), ([2, 5], [1, 4])]
python list generator
No comments:
Post a Comment