简体   繁体   English

整数的科学记数法

[英]Scientific notation to integers

I have a file in which values are in scientific notation 3.198304894802781462e+00 .我有一个文件,其中的值采用科学记数法 3.198304894802781462e+00 。 I want to convert these in integers.我想将这些转换为整数。 I have tried this:我试过这个:

data = [int(float(number))
            for line in open('data.txt', 'r')
                for number in line.split()]

Error:错误:

could not convert string to int: '1.874475383557408747e+01,3.627623082212955374e+00,9.037237691778705084

you can use the context manager to read from your file:您可以使用上下文管理器从您的文件中读取:

data = []
with open('data.txt', 'r') as fp:
    for line in fp.readlines():
        for number in line.split(','):
            data.append(int(float(number.strip())))

if you want to append the data list to your file:如果要将数据列表附加到文件中:

with open('data.txt', 'a') as fp:
    fp.write(",".join(str(e) for e in data))

Judging by your error message, your numbers are delimited by , , not whitespace.通过您的错误信息来看,您的号码被分隔,而不是空白。 You must therefore use line.split(',') instead.因此,您必须改用line.split(',')

with open('data.txt', 'r') as in_stream:
    data = [
        int(float(number))
        for line in in_stream
        for number in line.split(',')
    ]

try something like this.尝试这样的事情。 you need to split the string and then apply the float function on every item:您需要拆分字符串,然后在每个项目上应用浮点函数:

a = '1.874475383557408747e+01,3.627623082212955374e+00,9.037237691778705084'
b = a.split(',')
print(b)

for n in b:
    print(float(n))

or simply:或者干脆:

res = [float(n) for n in a.split(',')]

I assumed that you have your data as string but from your example this should work:我假设您将数据作为字符串,但从您的示例来看,这应该有效:

data = [int(float(number))
            for line in open('data.txt', 'r')
                for number in line.split(',')]

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

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