Что такое интуиция за кодом ниже python, где идентичный код дает два разных выхода?
import itertools as it
import collections
# Chained list not getting printed
l1 = [x for x in range(10)]
l2 = [y*2 for y in range(10)]
l3 = it.chain(l1,l2)
l4 = collections.Counter(l3)
print(list(l3))
print(l4)
# Counter dict not getting printed
l1 = [x for x in range(10)]
l2 = [y*2 for y in range(10)]
l3 = it.chain(l1,l2)
print(list(l3))
l4 = collections.Counter(l3)
print(l4)
Выход
[]
Counter({0: 2, 2: 2, 4: 2, 6: 2, 8: 2, 1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 10: 1, 12: 1, 14: 1, 16: 1, 18: 1})
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Counter()
Обновление
Путем явного преобразования объекта itertools.chain
в list
выходы одинаковые.
import itertools as it
import collections
l1 = [x for x in range(10)]
l2 = [y*2 for y in range(10)]
l3 = it.chain(l1,l2)
print(type(l3))
l5 = list(l3)
l4 = collections.Counter(l5)
print(l5)
print(l4)
l1 = [x for x in range(10)]
l2 = [y*2 for y in range(10)]
l3 = it.chain(l1,l2)
l5 = list(l3)
print(l5)
l4 = collections.Counter(l5)
print(l4)
Выход
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Counter({0: 2, 2: 2, 4: 2, 6: 2, 8: 2, 1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 10: 1, 12: 1, 14: 1, 16: 1, 18: 1})
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Counter({0: 2, 2: 2, 4: 2, 6: 2, 8: 2, 1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 10: 1, 12: 1, 14: 1, 16: 1, 18: 1})