Ushbu maqolada Python zip ( ) funksiyasini qo'llanilishi haqida misollar bilan ma'lumot olasiz
Elementlar bo‘yicha ikkita ro‘yxatni juftlarga ajratish:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
# [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
2. Ro‘yxatlarni “ajratib olish” (unzipping)
combined = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
names, ages = zip(*combined)
print(names) # ('Alice', 'Bob', 'Charlie')
print(ages) # (25, 30, 35)
3. Bir nechta ro‘yxatlar ustida bir vaqtda yurish
subjects = ['Math', 'Science', 'English']
scores = [88, 92, 85]
for subject, score in zip(subjects, scores):
print(f"{subject}: {score}")
# Math: 88
# Science: 92
# English: 85
4. Lug‘at (dictionary) yaratish
fields = ["name", "last_name", "age", "job"]
values = ["John", "Doe", "45", "Python Developer"]
person = dict(zip(fields, values))
print(person)
# {'name': 'John', 'last_name': 'Doe', 'age': '45', 'job': 'Python Developer'}
5. Bir nechta ro‘yxatni birlashtirish
letters = ["a", "b", "c"]
numbers = [1, 2, 3]
floats = [0.1, 0.2, 0.3]
combined = list(zip(letters, numbers, floats))
print(combined)
# [('a', 1, 0.1), ('b', 2, 0.2), ('c', 3, 0.3)]
6. Lug‘atni yangilash
new_job = ["Python Consultant"]
field = ["job"]
person.update(zip(field, new_job))
print(person)
# {'name': 'John', 'last_name': 'Doe', 'age': '45', 'job': 'Python Consultant'}
7. Parallel tartiblash (sorting)
letters = ["b", "a", "d", "c"]
numbers = [2, 4, 3, 1]
data = list(zip(letters, numbers))
data.sort()
print(data)
# [('a', 4), ('b', 2), ('c', 1), ('d', 3)]
Yoki qisqaroq:print(sorted(zip(letters, numbers)))
8. Juftdagi elementlar bilan hisob-kitob
total_sales = [52000.00, 51000.00, 48000.00]
prod_cost = [46800.00, 45900.00, 43200.00]
for sales, costs in zip(total_sales, prod_cost):
profit = sales - costs
print(f"Total profit: {profit}")
# Total profit: 5200.0
# Total profit: 5100.0
# Total profit: 4800.0
9. Parallel iteratsiya qilish
dict_one = {"name": "John", "last_name": "Doe", "job": "Python Consultant"}
dict_two = {"name": "Jane", "last_name": "Doe", "job": "Community Manager"}
for (k1, v1), (k2, v2) in zip(dict_one.items(), dict_two.items()):
print(k1, "->", v1)
print(k2, "->", v2)
10. strict=True parametri (Python 3.10+)list(zip(range(5), range(100), strict=True))
# ValueError: zip() argument 2 is longer than argument 1
Agar ro‘yxatlar uzunliklari teng bo‘lmasa, ValueError xatosi chiqariladi.
zip()
funksiyasi — Python’da ro‘yxatlar, lug‘atlar va boshqa iteratsiyalar ustida parallel ishlash uchun juda qulay vosita. Uning yordamida kod qisqa, tushunarli va samarali yoziladi.
P. S. Manba sifatida pythonclcoding.medium.com dan foydalanildi.
Muallif:
Muallif: