简体   繁体   English

Python 3:如何从浮点数创建列表?

[英]Python 3: how to create list out of float numbers?

Anyone knows how can I solve this issue? 谁知道我该如何解决这个问题? I have the following code. 我有以下代码。

result=[]
for i in range(len(response_i['objcontent'][0]['rowvalues'])):
    lat = response_i['objcontent'][0]['rowvalues'][i][0]
    print(lat)
    for i in lat:
        result.append(i)     
    print (result)

Following is the output of print(lat) : 以下是print(lat)的输出:

92.213725
191.586143
228.981615
240.353291

and following is the output of print(result) : 以下是print(result)的输出:

['9', '2', '.', '2', '1', '3', '7', '2', '5', '1', '9', '1', '.', '5', '8',
'6', '1', '4', '3', '2', '2', '8', '.', '9', '8', '1', '6', '1', '5', '2',
'4', '0', '.', '3', '5', '3', '2', '9', '1']

I expected to get the output in following format: 我希望得到以下格式的输出:

[92.213725, 191.586143, 228.981615, 240.353291]

Anyone knows how to fix this issue? 有人知道如何解决此问题吗?

Thanks 谢谢

So, your error is that instead of simply adding your latitute to the list, you are iterating over each character of the latitude, as a string, and adding that character to a list. 因此,您的错误是,您不是将您的latitute数简单地添加到列表中,而是以字符串的形式遍历纬度的每个字符,然后将该字符添加到列表中。

result=[]
for value in response_i['objcontent'][0]['rowvalues']:
    lat = value[0]
    print(lat)
    result.append(float(lat))

print (result)

Besides that, using range(len(...))) is the way things have to be done in almost all modern languages, because they either don't implement a "for ...each" or do it in an incomplete or faulty way. 除此之外,几乎所有现代语言都必须使用range(len(...))),因为它们要么未实现“ for ... each”,要么以不完整或错误的方式。

In Python, since the beginning it is a given that whenever one wants a for iteration he wants to get the items of a sequence, not its indices (for posterior retrieval of the indices). 在Python中,从一开始就假定,只要有人想要for迭代,他就想要获得序列的项,而不是其索引(用于索引的后检索)。 Some auxiliar built-ins come in to play to ensure you just interate the sequence: zip to mix one or more sequences, and enumerate to yield the indices as well if you need them. 一些辅助内置函数可用来确保您仅插入序列:压缩以混合一个或多个序列,并在需要时枚举以产生索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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