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

Python - Các phạm vi liên tiếp của K lớn hơn N

Khi cần lấy các phạm vi liên tiếp của 'K' lớn hơn 'N', ta dùng thuộc tính enumerate và lặp đơn giản.

Ví dụ

my_list = [3, 65, 33, 23, 65, 65, 65, 65, 65, 65, 65, 3, 65]
print("The list is:")
print(my_list)

K = 65
N = 3
print("The value of K is")
print(K)
print("The value of N is")
print(N)

my_result = []
beg, end = 0, 0
previous = 1

for index, element in enumerate(my_list):
    if element == K:
        end = index
        if previous != K:
            beg = index
    else:
        if previous == K and end - beg + 1 >= N:
            my_result.append((beg, end))
        previous = element

print("The result is:")
print(my_result)

Đầu ra

The list is: [3, 65, 33, 23, 65, 65, 65, 65, 65, 65, 65, 3, 65]
The value of K is 65
The value of N is 3
The result is: [(4, 10)]

Giải thích

  • Định nghĩa list, K, N, hiển thị.
  • List rỗng, giá trị previous, begin, end.
  • Lặp list bằng enumerate.
  • Nếu phần tử = K, cập nhật end, begin.
  • Ngược lại, nếu previous = K và độ dài >= N, thêm (beg, end).
  • Cập nhật previous, hiển thị kết quả.