Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หา Index ของค่า None ในลิสต์ Python

ค้นหาตำแหน่งของ None ในลิสต์

ลิสต์อาจมีค่า None ต้องการหา Index ทั้งหมดที่มีค่า None

วิธีที่ 1: ใช้ range + len


lst = ['Sun','Mon',None,'Wed',None,None]
indices = [i for i in range(len(lst)) if lst[i] is None]
print(indices)  # [2,4,5]

วิธีที่ 2: ใช้ enumerate


indices = [i for i, val in enumerate(lst) if val is None]
print(indices)  # [2,4,5]