简体   繁体   English

列表是不可变的? 无法转换字符串列表 ---> 浮点数列表

[英]List is immutable? Cannot convert list of strings ---> list of floats

I have a list of values, titled 'list', with values 23.4158, 25.3817, 26.4629, 26.8004, 26.6582, 27.7, 27.8476, 28.025.我有一个名为“列表”的值列表,其值为 23.4158、25.3817、26.4629、26.8004、26.6582、27.7、27.8476、28.025。 Each value is a string, not a float.每个值都是一个字符串,而不是浮点数。 Thus, I would like to convert this to a list of floats.因此,我想将其转换为浮点数列表。

When I create a for loop to reassign the strings as floats, using the float() function, within the loops it shows me that the str has been successfully converted to a float.当我创建一个 for 循环以将字符串重新分配为浮点数时,在循环中使用 float() function,它显示 str 已成功转换为浮点数。 But when I check the type outside the loop, it shows me they are still strings.但是当我检查循环外的类型时,它告诉我它们仍然是字符串。

for i in list:
    i = float(i)
    print(i,"=", type(i))
print(type(list[0]))

HOWEVER.然而。 When I create an empty list (new_list), and append the converted floats into said list, it shows exactly what I want.当我创建一个空列表 (new_list) 和 append 转换后的浮点数到所述列表中时,它完全显示了我想要的。 In other words, the str--->float conversion is successful.也就是说str--->float转换成功。 Code as such:代码如下:

new_list = list()
for i in list:
    i = float(i)
    print(i,"=", type(i))
    new_list.append(i)
print(type(new_list[0]))

Why is it that the reassignment does not 'stick' unless the values are appended to new_list?为什么除非将值附加到 new_list,否则重新分配不会“坚持”? Lists are mutable, so the old list should be able to be modified.列表是可变的,所以旧列表应该可以修改。 Am i missing something?我错过了什么吗?

The reassignment does not "stick" because you are not converting the item inside the list, you are converting i , which is another value inside the loop, completely detached from the list object.重新分配不会“坚持”,因为您没有转换列表内的项目,而是转换i ,这是循环内的另一个值,完全与list object 分离。 You are just converting a new variable i to float , you are not converting the item from within the list.您只是将新变量i转换为float ,而不是从列表中转换项目。 The variable i is a new variable and python just copied the value from the item inside the new variable i .变量i是一个新变量, python 只是从新变量i内的项目中复制了 You are not converting the item from the list, you are converting a new variable i that has the same value as the item that the loop is currently at.您没有转换列表中的项目,而是转换了一个新变量i ,该变量与循环当前所在的项目具有相同的值。

If you want to convert the item from withing the list using a for loop, you must target the item itself using its index:如果要使用 for 循环从列表中转换项目,则必须使用其索引定位项目本身:

values = [
    "23.4158", "25.3817", "26.4629", "26.8004", "26.6582", "27.7", "27.8476", "28.025"
]

for i in range(len(values)):
    values[i] = float(values[i])

print(values)
print(type(values[0]))

The reason why it works when appending to a list is because you are appending the newly converted i , which indeed, is a float.它在附加到列表时起作用的原因是因为您正在附加新转换的i ,这确实是一个浮点数。

I suggest reading the following:我建议阅读以下内容:

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

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