hàm enumerate trong python là gì
- User
hàm enumerate trong python là gì
Assistant
enumerate()là một hàm built-in trong Python dùng để duyệt qua một iterable (như list, tuple, string) và trả về cả index lẫn giá trị của từng phần tử.Cú pháp:
enumerate(iterable, start=0)Cách hoạt động:
Khi dùng
enumerate(), bạn sẽ nhận được một enumerate object chứa các tuple (index, value):# Ví dụ cơ bản fruits = ['táo', 'cam', 'chuối'] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # Output: # 0: táo # 1: cam # 2: chuốiTùy chỉnh index bắt đầu:
# Bắt đầu từ 1 thay vì 0 for index, fruit in enumerate(fruits, start=1): print(f"{index}: {fruit}") # Output: # 1: táo # 2: cam # 3: chuối
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.