For Loop And Zip In Python
Solution 1:
zip allows you to iterate two lists at the same time, so, for example, the following code
letters = ['a', 'b', 'c']
numbers = [1, 2, 3]
for letter, number inzip(letters, numbers):
print(f'{letter} -> {number}')
gives you as output
a ->1
b ->2
c ->3
when you iterate with zip, you generate two vars, corresponding to the current value of each loop.
Solution 2:
Q1: zip
is used to merge 2 lists together. It returns the first element of each list, then 2nd element of each list, etc. This is a trick to consider the two lists as key and data to create a dictionary.
Q2: this is a dictionary (hash), using a method called "dict comprehension". It creates the dictionary shown as the output. If assigned to a variable d
, d['a'] = 10
, etc.
Solution 3:
just print the line you don't understand to make it clearer...
first we define 2 arrays
Class_numbers=np.array(['a','b','c'])
['a','b','c']students_per_class=np.array([10,20,30])
[10,20,30]
zip just add them together like
[('a', 10), ('b', 20), ('c', 30)]
now we iterate on each element with x and y and create a dict
object (hash map) { key : value}
{'a': 10, 'c': 30, 'b': 20}
Solution 4:
zip is useful to enumerate the elements in the 2 different list and make a single list
example :
x: y for x, y in zip(Class_numbers, students_per_class)
explanation:
- the element form Class_number is assigned to x which is a "Key" for the dictionary and the students_per_class is assigned to y which is a "value
- until the loop end it will iterate to dictionary.
Solution 5:
there is a trick in using zip:
letters = ('A', 'B', 'C')
numbers = ('1', '2', '3')
let_num = zip(letters, numbers)
use the list() function to display zip:
print(list(let_num))
above code will produce
[('A', '1'), ('B', '2'), ('C', '3')]
please note that, if you want to print again, this will not print anything since we already consumed the zip
print(list(let_num))
Post a Comment for "For Loop And Zip In Python"