简体   繁体   中英

How to get index and value of an item in python list?

I have a list like this:

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

I want to get any number >0.1 and put them as well as their list index in another list. In this list like this:

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

I have tried this code so far, which has not been very useful:

another_lst = []

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

Need help. Thanks!

The error you're getting is because you're trying to do float(None) . Have a check at the beginning of the for-loop to filter out those Nones:

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

Also, use another_lst.append() function instead of += . Sometimes the latter can lead to unexpected behaviour.

You can try this:

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]

Output:

[[4, '0.141675556588'], [9, '0.268087046988']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM