Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将数组中的文本值转换为float和add_Python_Arrays_For Loop - Fatal编程技术网

如何在python中将数组中的文本值转换为float和add

如何在python中将数组中的文本值转换为float和add,python,arrays,for-loop,Python,Arrays,For Loop,我有一个包含以下值的文本文件: 120 25 50 149 33 50 095 41 50 093 05 50 081 11 50 我提取了第一列中的值,然后放入一个数组:adjusted 如何将值从text转换为float,并使用for循环为每个值添加5 我期望的输出是: 125 154 100 098 086 这是我的密码: adjusted = [(adj + (y)) for y in floats] A1 = adjusted[0:1] A2 = adjusted[1:2] A3

我有一个包含以下值的文本文件:

120 25 50
149 33 50
095 41 50
093 05 50
081 11 50
我提取了第一列中的值,然后放入一个数组:adjusted

如何将值从text转换为float,并使用for循环为每个值添加5

我期望的输出是:

125
154
100
098
086
这是我的密码:

adjusted = [(adj + (y)) for y in floats]

A1 = adjusted[0:1]
A2 = adjusted[1:2]
A3 = adjusted[2:3]
A4 = adjusted[3:4]
A5 = adjusted[4:5]
print A1
print A2
print A3
print A4
print A5


A11= [float(x) for x in adjusted]
FbearingBC = 5 + float(A11)
print FbearingBC
它给我错误,它说我不能添加浮点和字符串
pliz帮助

假设您有:

adjusted = ['120', '149', '095', ...]
转换为浮点并添加五的最简单方法是:

converted = [float(s) + 5 for s in adjusted]
这将创建一个新列表,迭代旧列表中的每个字符串,将其转换为float并添加5

将列表中的每个值分配给一个单独的名称A1等不是一个好方法;如果您的条目比预期的多或少,则此操作将中断。通过索引(例如调整后的[0])访问每个值或对其进行迭代(例如,针对调整后的中的值)更干净,也更不容易出错

这是一个列表理解,因此它在一行中完成了所有转换为浮点、添加5以及将它们附加到列表的功能。但是,如果您的所有数字都是整数,则应将其转换为整数,这样您就不会拥有所有的.0。

此代码应适用于:

with open('your_text_file.txt', 'rt') as f:
    for line in f:
        print(float(line.split()[0]) + 5)
它将显示:

125.0
154.0
100.0
98.0
86.0
或者您需要列表中的所有值:

with open('your_text_file.txt', 'rt') as f:
    values = [float(line.split()[0]) + 5 for line in f]
print (values)

由于您正在从文件中读取数据,因此可以按如下方式执行:

with open('data.txt', 'r+') as f: # where data.txt is the file containing your data
    for line in f.readlines(): # Get one line of data from the file
        number = float(line.split(' ')[0]) # Split your data by ' ' and get the first number.
        print "%03d" % (number + 5) # Add 5 to it and then print using the format "%03d"

希望这有帮助。

您可以按以下方式进行转换:floatnumber\u string。另外,它在哪一行给你错误?在那一行:FbearingBC=5+floatA11
with open('data.txt', 'r+') as f: # where data.txt is the file containing your data
    for line in f.readlines(): # Get one line of data from the file
        number = float(line.split(' ')[0]) # Split your data by ' ' and get the first number.
        print "%03d" % (number + 5) # Add 5 to it and then print using the format "%03d"