ขึ้นอยู่กับความต้องการของการวิเคราะห์ข้อมูล เราอาจต้องตรวจสอบการมีอยู่ของตัวเลขลำดับในคอนเทนเนอร์ข้อมูล Python ในโปรแกรมด้านล่างเราจะตรวจสอบว่าระหว่างองค์ประกอบของ Alist มีตัวเลขติดต่อกันหรือไม่
ด้วย range และ sorted
ฟังก์ชัน sorted จะจัดเรียงองค์ประกอบของลิสต์ในลำดับที่เรียงแล้ว เราจึงใช้ฟังก์ชัน range โดย取ค่าต่ำสุดและสูงสุดจากลิสต์โดยใช้ min และ max เราเก็บผลลัพธ์ของการดำเนินการข้างต้นในสองลิสต์และเปรียบเทียบความเท่ากัน
ตัวอย่าง
listA = [23, 20, 22, 21, 24]
sorted_list = sorted(listA)
range_list = list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")
# Checking again
listB = [23, 20, 13, 21, 24]
sorted_list = sorted(listB)
range_list = list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")
Output
การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -
listA has consecutive numbers ListB has no consecutive numbers
ด้วย numpy diff และ sorted
ฟังก์ชัน diff ใน numpy หาความต่างระหว่างตัวเลขแต่ละตัวหลังจากเรียงแล้ว เราหาผลรวมของความต่างเหล่านี้ จะตรงกับความยาวของลิสต์ถ้าตัวเลขทั้งหมดติดต่อกัน
ตัวอย่าง
import numpy as np
listA = [23, 20, 22, 21, 24]
sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")
# Checking again
listB = [23, 20, 13, 21, 24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")
Output
การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -
listA has consecutive numbers ListB has no consecutive numbers