Python 如何解决TypeError:'float'对象不可迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49998463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to solve TypeError: 'float' object is not iterable
提问by FlyingBurger
How can I transfer
我该如何转移
A = [0.12075357905088335, -0.192198145631724, 0.9455373400335009, -0.6811922263715244, 0.7683786941009969, 0.033112227984689206, -0.3812622359989405]
to
到
A = [[0.12075357905088335], [-0.192198145631724], [0.9455373400335009], [-0.6811922263715244], [0.7683786941009969], [0.033112227984689206], [-0.3812622359989405]]
I tried to the code below but an error occurred:
我尝试了下面的代码,但发生了错误:
new = []
for i in A:
new.append.list(i)
TypeError: 'float' object is not iterable
TypeError: 'float' object is not iterable
Could anyone help me?
有人可以帮助我吗?
回答by Ivan Vinogradov
tl;dr
tl;博士
Try list comprehension, it is much more convenient:
尝试列表理解,它更方便:
new = [[i] for i in A]
Explanation
解释
You are getting TypeError
because you cannot apply list()
function to value of type float
. This functiontakes an iterable as a parameter and float
is not an iterable.
你得到的TypeError
是因为你不能将list()
函数应用于 type 的值float
。该函数将一个可迭代对象作为参数,float
而不是一个可迭代对象。
Another mistake is that you are using new.append._something
instead of new.append(_something)
: append
is a methodof a list
object, so you should provide an item to add as a parameter.
另一个错误是,你正在使用new.append._something
的不是new.append(_something)
:append
是方法一的list
对象,所以你应该提供添加作为参数的项目。
回答by stasdeep
You have a mistake, try:
您有错误,请尝试:
new = []
for i in A:
new.append([i])
Here is more beautiful solution:
这是更漂亮的解决方案:
new = [[i] for i in A]
回答by jpp
list.append
is a method which requires an argument, e.g. new.append(i)
or, in this case new.append([i])
.
list.append
是一种需要参数的方法,例如new.append(i)
or,在这种情况下new.append([i])
。
A list comprehension is a better idea, see @IvanVinogradov's solution.
列表理解是一个更好的主意,请参阅@IvanVinogradov 的解决方案。
If you are happy using a 3rd party library, consider numpy
for a vectorised solution:
如果您对使用 3rd 方库感到满意,请考虑numpy
使用矢量化解决方案:
import numpy as np
A = [0.12075357905088335, -0.192198145631724, 0.9455373400335009, -0.6811922263715244, 0.7683786941009969, 0.033112227984689206, -0.3812622359989405]
A = np.array(A)[:, None]
print(A)
# [[ 0.12075358]
# [-0.19219815]
# [ 0.94553734]
# [-0.68119223]
# [ 0.76837869]
# [ 0.03311223]
# [-0.38126224]]
回答by Aryan Daftari
I think you are using like that:
我想你是这样使用的:
my_data=b['dataset']['data'][0][1]
useful_data=[i[1] for i in my_data]
So when you compile it gives you an error:
所以当你编译它会给你一个错误:
TypeError: 'float' object is not iterable
类型错误:“浮动”对象不可迭代
Try only:
仅尝试:
my_data=b['dataset']['data']
Then you will get your data.
然后你会得到你的数据。