Contoh program : Program Python untuk Iterasi Melalui Dua Daftar Secara Paralel

0
(0)

Contoh 1: Menggunakan zip (Python 3+)

list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']

for i, j in zip(list_1, list_2):
    print(i, j)

Keluaran

1 a
2 b
3 c

Loop berjalan hingga daftar yang lebih pendek berhenti (kecuali jika kondisi lain dilewati).


Contoh 2: Menggunakan itertools (Python 2+)

import itertools

list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']

# loop until the short loop stops
for i,j in itertools.izip(list_1,list_2):
    print i,j

print("n")

# loop until the longer list stops
for i,j in itertools.izip_longest(list_1,list_2):
    print i,j

Keluaran

1 a
2 b
3 c


1 a
2 b
3 c
4 None

izip_longest() biarkan loop berjalan sampai daftar terpanjang berhenti.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.