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

Python - Tìm tất cả chuỗi là chuỗi con của danh sách chuỗi cho trước

Khi cần tìm tất cả các chuỗi là chuỗi con của một danh sách chuỗi cho trước, ta sử dụng thuộc tính set và list.

Ví dụ

my_list_1 = ["Hi", "there", "how", "are", "you"]
my_list_2 = ["Hi", "there", "how", "have", "you", 'been']

print("The first list is:")
print(my_list_1)
print("The second list is:")
print(my_list_2)

my_result = list(set([elem_1 for subset_1 in my_list_1 for elem_1 in my_list_2 if elem_1 in subset_1]))
print("The result is:")
print(my_result)

Đầu ra

The first list is: ['Hi', 'there', 'how', 'are', 'you']
The second list is: ['Hi', 'there', 'how', 'have', 'you', 'been']
The result is: ['there', 'you', 'Hi', 'how']

Giải thích

  • Định nghĩa hai list chuỗi và hiển thị.
  • Lặp qua hai list, dùng set để lấy giá trị duy nhất.
  • Chuyển thành list.
  • Gán vào biến và hiển thị.