Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python mask list dùng giá trị từ list khác

Khi cần mask list nhờ giá trị từ list khác, dùng list comprehension.

Ví dụ

my_list = [5, 6, 1, 9, 11, 0, 4]
print("The list is:")
print(my_list)

search_list = [2, 10, 6, 3, 9]
result = [1 if element in search_list else 0 for element in my_list]
print("The result is:")
print(result)

Đầu ra

The list is: [5, 6, 1, 9, 11, 0, 4]
The result is: [0, 1, 0, 1, 0, 0, 0]

Giải thích

  • Định nghĩa list, hiển thị.
  • Định nghĩa list tìm kiếm.
  • List comprehension: nếu phần tử có trong search_list thì 1, ngược lại 0.
  • Gán kết quả, hiển thị.