[英]Converting list of strings to floats and add 1
I have parsed my input to this list: 我已将我的输入解析为此列表:
lst = ['6,3', '3,2', '9,6', '4,3']
How to change this list of strings to a list of floats? 如何将此字符串列表更改为浮动列表? While the numbers that are nw strings are not seperated by a .
虽然nw字符串的数字不是由a分隔的。 but by a ,
但是,
After that i would like to add 1 to every float. 之后,我想为每个浮点数添加1。 So that the ouput becomes:
这样输出就变成了:
lst = [7.3, 4.2, 10.6, 5.4]
You could use locale.atof(string)
which is a function designed to convert a string to a float, taking into account the locale settings, ie taking into account that in some cultures/languages the comma is used to make the decimal point, as opposed to a period. 你可以使用
locale.atof(string)
这是一个设计用于将字符串转换为float的函数,考虑到语言环境设置, 即考虑到在某些文化/语言中逗号用于生成小数点,如反对一段时期。
The list comprehension for this would then be something like this 对此的列表理解将是这样的
from locale import atof
a = ['6,3', '3,2', '9,6', '4,3']
b = [atof(i) + 1 for i in a]
Unfortunately, I cannot test that it works with a comma as my locale is set to use a period. 不幸的是,我无法测试它是否与逗号一起使用,因为我的语言环境设置为使用句点。
If you don't want to use locale.atof
then the code below will do a similar job by converting the comma to a period. 如果您不想使用
locale.atof
那么下面的代码将通过将逗号转换为句点来执行类似的工作。 You can replace the comma with a period using str.replace
. 您可以使用
str.replace
将句号替换为句点。
a = ['6,3', '3,2', '9,6', '4,3']
b = [float(i.replace(',', '.')) + 1 for i in a]
# [7.3, 4.2, 10.6, 5.3]
This list comprehension is equivalent to 这个列表理解相当于
a = ['6,3', '3,2', '9,6', '4,3']
b = []
for i in a:
j = float(i.replace(',', '.')) + 1
b.append(j)
What about: 关于什么:
l2 = [float(num.replace(',', '.')) + 1 for num in lst]
First you replace comma by dot in string, after that you cast to float and add 1 to result. 首先用字符串中的点替换逗号,然后转换为浮点数并将结果加1。 Operation is perfomed for each element in list.
对列表中的每个元素执行操作。
Using list comprehension: 使用列表理解:
lst = ['6,3', '3,2', '9,6', '4,3']
new_lst = [float(num.replace(',','.')) + 1 for num in lst]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.