如何在python列表中获取项的索引和值?

时间:2017-08-29 02:32:12

标签: python string list floating-point

我有一个这样的清单:

lst = [None,None,None,'0.141675556588',None,None,None,'0.268087046988']

我想得到任何数字> 0.1并将它们和列表索引放在另一个列表中。在这个列表中这样:

another_lst = [['3', 0.14], ['7', 0.26]]

到目前为止,我已尝试过这段代码,但这并不是很有用:

another_lst = []

for position, item in enumerate(lst):
    if float(item) > 0.1:
        another_lst += [position, item]

需要帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

您收到的错误是因为您尝试float(None)。在for循环的开头检查以过滤掉那些Nones:

for position, item in enumerate(a):
    if item is not None and float(item) > 0.1:
        another_lst.append([position, item])

另外,使用another_lst.append()函数代替+=。有时后者会导致意外行为。

答案 1 :(得分:1)

你可以试试这个:

lst = [None,None,"string", None,'0.141675556588',None,None,"hi how are you", None,'0.268087046988']

positions = [[i, a] for i, a in enumerate(lst) if a is not None and not ''.join(a.split()).isalpha() and float(a) > 0.1]

输出:

[[4, '0.141675556588'], [9, '0.268087046988']]
相关问题