Khi cần tạo list tuple, phần tử 1 là số, phần tử 2 là bình phương, dùng list comprehension.
Minh họa:
Ví dụ
my_list = [23, 42, 67, 89, 11, 32]
print("The list is ")
print(my_list)
print("The resultant tuple is :")
my_result = [(val, pow(val, 2)) for val in my_list]
print(my_result)
Kết quả
The list is [23, 42, 67, 89, 11, 32] The resultant tuple is : [(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]
Giải thích
- Định nghĩa list, hiển thị console.
- List comprehension dùng 'pow' tìm bình phương.
- Chuyển list.
- Hiển thị output console.