在Python的给定列表中查找无值的索引
很多时候在处理数据分析时,我们可能会遇到列表中的None值。这些值不能直接在数学运算和字符串运算等中使用。因此,我们需要找到它们的位置并进行转换或有效使用。
用range()
结合使用range和len函数,我们可以将每个元素的值与None进行比较,并捕获其索引位置。当然,我们使用for循环设计来实现这一点。
示例
listA = ['Sun', 'Mon',None, 'Wed', None, None]
# Given list
print("Given list : ",listA)
# Using range
positions = [i for i in range(len(listA)) if listA[i] == None]
# Result
print("None value positions : ",positions)输出结果
运行上面的代码给我们以下结果-
Given list : ['Sun', 'Mon', None, 'Wed', None, None] None value positions : [2, 4, 5]
用枚举
我们还可以使用列举ech元素的枚举函数。然后,我们将每个元素与None值进行比较,并按如下所示在程序中选择其位置。
示例
listA = ['Sun', 'Mon',None, 'Wed', None, None]
# Given list
print("Given list : ",listA)
# Using enumarate
positions = [i for i, val in enumerate(listA) if val == None]
# Result
print("None value positions : ",positions)输出结果
运行上面的代码给我们以下结果-
Given list : ['Sun', 'Mon', None, 'Wed', None, None] None value positions : [2, 4, 5]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语