[英]Changing all strings except one in a list of lists to a float
I have a list of lists:我有一个列表列表:
LofL = [["string", "number", "number", "number"], ["string", "number", "number", "number"], ...]
and im trying to turn the numbers within the list of lists to floats instead of strings.我试图将列表列表中的数字转换为浮点数而不是字符串。 Each list of list is not equal in length.
列表的每个列表的长度都不相等。 So far I have:
到目前为止我有:
for sublist in LofL:
sublist[1:] = float(sublist[1:])
but I'm getting the error float argument must be a string or real number not a list .但我收到错误float argument must be a string or real number not a list 。 This works for single numbers if I do
sublist[1] = float(sublist[1])
but I'm unsure of how to include all numbers in each list of lists without the [1:] indexing.如果我执行
sublist[1] = float(sublist[1])
这适用于单个数字,但我不确定如何在没有 [1:] 索引的情况下将所有数字包含在每个列表列表中。
for sublist in LofL:
for i in range(1, len(sublist)):
sublist[i]=float(sublist[i])
Explanation: Your initial code sublist[1:]=float(sublist[1:]
will not work as sublist[1:]
is a list and you cannot turn list to a float.说明:您的初始代码
sublist[1:]=float(sublist[1:]
将不起作用,因为sublist[1:]
是一个列表,您不能将 list 转换为 float。
So the for i in range(1, len(sublist)
will iterate through each element in your sublist
then with each iteration we will convert sublist[i]=float(sublist[i]
into float. Because you specified that the first item of sublist does not need to change hence we are starting our loop from 1因此
for i in range(1, len(sublist)
将遍历子列表中的每个元素,然后在每次迭代中我们将sublist
sublist[i]=float(sublist[i]
转换为 float。因为您指定了第一项子列表不需要更改,因此我们从 1 开始循环
This is very similar to the other answer here.这与此处的其他答案非常相似。 I'm just including it because it seems like the reassignment of a slice of the list is what you were going for in your original code:
我只是包括它,因为它似乎是您在原始代码中想要的,重新分配列表的一部分:
LofL = [["string", '1', '2', '3'], ["string", '4', '5', '6', '7']]
for sublist in LofL:
sublist[1:] = map(float, sublist[1:])
print(LofL)
# [['string', 1.0, 2.0, 3.0], ['string', 4.0, 5.0, 6.0, 7.0]]
The excellent answer from @Mark solves your particular problem. @Mark 的出色回答解决了您的特定问题。 However, there is an implicit assumption that the first element of each sub-list should be ignored and that subsequent elements can be converted to float.
但是,有一个隐含的假设,即应忽略每个子列表的第一个元素,并且可以将后续元素转换为浮点数。
Here's a simple double loop that will try to convert all elements.这是一个简单的双循环,它将尝试转换所有元素。 This would allow for the 'string' component to be anywhere in the list.
这将允许“字符串”组件位于列表中的任何位置。
LofL = [["string", "42", "42", "1"], ["string", "2.5", "100", "20"], [5, 'string']]
for e in LofL:
for i, v in enumerate(e):
try:
e[i] = float(v)
except ValueError:
pass
print(LofL)
Output: Output:
[['string', 42.0, 42.0, 1.0], ['string', 2.5, 100.0, 20.0], [5.0, 'string']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.