Created
December 25, 2021 10:25
-
-
Save ruslanmv/f16b629c4a73c8aa95807b2bdb31393a to your computer and use it in GitHub Desktop.
Tricks with Zip in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Tuple: | |
# Capture arbitrarily long list | |
values = 1,2,3,4,5 | |
a, b, *rest = values | |
# Discard the rest | |
a, b, *_ = values | |
## Zip: | |
# "pairs" up the elements of list | |
seq1 = ['foo','bar','baz'] | |
seq2 = ['one','two','three'] | |
for i in list(zip(seq1, seq2)): | |
a,b = i | |
print('{}-{}'.format(b,a)) | |
# Unzip a sequence | |
pitchers = [('Nolan','Ryan'), | |
('Roger','Clemens'), | |
('Schilling','Curt')] | |
first_names, last_name = zip(*pitchers) | |
# Create Dicts from Sequences | |
mapping = {} | |
key_list = ['Apple','Orange','Banana'] | |
value_list = [1, 4, 8] | |
for key, value in zip(key_list, value_list): | |
mapping[key] = value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment