简体   繁体   中英

How to change list elements of specific indices to float in a list of lists (Python)?

I have a NumPy ndarray array that has been converted to a list of lists array = [list(ele) for ele in array] . I also have a list indexes that is entered into my function to_float as a parameter specifying the indices of elements within a list for all lists that must not be effected by the code in my function. The function has to convert all elements within all lists to float not specified by indices in indexes .

For example, my array (converted to lists) and indexes could be:

array = [['Hi', 'how', 'are', 'you', '4.65', '5.789', 'eat', '9.021'], ['its', 'not', 'why', 'you', '6.75', '5.89', 'how', '2.10'], 
['On', 'woah', 'right', 'on', '7.45', '9.99', 'teeth', '2.11']]
indexes = [0, 1, 2, 3, 6]

I now have to convert all elements in all my lists that are not indices specified in indexes to float values.

Desired output:

[['Hi', 'how', 'are', 'you', 4.65, 5.789, 'eat', 9.021], ['its', 'not', 'why', 'you', 6.75, 5.89, 'how', 2.10], 
['On', 'woah', 'right', 'on', 7.45, 9.99, 'teeth', 2.11]]

As you can see, elements with indices 4, 5, 7 in all lists were converted to float as their indices were not in indexes .

So how could I do this?

You can use enumerate and list comprehension:

array = [
    ["Hi", "how", "are", "you", "4.65", "5.789", "eat", "9.021"],
    ["its", "not", "why", "you", "6.75", "5.89", "how", "2.10"],
    ["On", "woah", "right", "on", "7.45", "9.99", "teeth", "2.11"],
]
indexes = [0, 1, 2, 3, 6]

array = [
    [float(val) if i not in indexes else val for i, val in enumerate(subl)]
    for subl in array
]
print(array)

Prints:

[['Hi', 'how', 'are', 'you', 4.65, 5.789, 'eat', 9.021], 
 ['its', 'not', 'why', 'you', 6.75, 5.89, 'how', 2.1], 
 ['On', 'woah', 'right', 'on', 7.45, 9.99, 'teeth', 2.11]]

Note: to speed up, you can convert indexes to set .

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