[英]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]
.我有一个 NumPy ndarray
array
,该数组已转换为列表列表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.我还有一个列表
indexes
,它作为参数输入到我的 function to_float
中,为所有列表中的元素索引指定列表中的元素索引,这些列表不得受我的 function 中的代码影响。 The function has to convert all elements within all lists to float
not specified by indices in indexes
. function 必须将所有列表中的所有元素转换为未由索引中的
indexes
指定的float
。
For example, my array
(converted to lists) and indexes
could be:例如,我的
array
(转换为列表)和indexes
可以是:
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.我现在必须将所有列表中不是索引中指定的
indexes
的所有元素转换为float
值。
Desired output:所需的 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
.如您所见,所有列表中索引为 4、5、7 的元素都被转换为
float
,因为它们的索引不在indexes
中。
So how could I do this?那么我该怎么做呢?
You can use enumerate
and list comprehension:您可以使用
enumerate
和列表理解:
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
.注意:为了加快速度,您可以将
indexes
转换为set
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.