Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Python: Taking 3 elements from one list using `zip()`

2020.03.09 - poniedziałek / kategoria: Python / tagi: python /

Taking 3 elements from one list

BTW: Python 3 needs soetime to use list().

Using list - doesn't work

a = [1,2,3,4,5,6,7,8,9]

print('A:', list(zip(a, a, a)) )

Using three iter() (iterating) - doesn't work

it_1 = iter(a) 
it_2 = iter(a)
it_3 = iter(a)

print('B:', list(zip(it_1, it_2, it_3)) )

Using one iter() (iterating) - works

it = iter(a)
print('C:', list(zip(it, it, it)) )

Using slicing - works

print('list:', a[::3])  # every three items - starting at 0
print('list:', a[1::3]) # every three items - starting at 1
print('list:', a[2::3]) # every three items - starting at 2

print('wynik:', list(zip(a[::3], a[1::3], a[2::3])) )

Result

A: [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9)]

B: [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9)]

C: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

list: [1, 4, 7]
list: [2, 5, 8]
list: [3, 6, 9]
D: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury