RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1608906
Accepted
KLYSTRON
KLYSTRON
Asked:2025-03-19 00:42:43 +0000 UTC2025-03-19 00:42:43 +0000 UTC 2025-03-19 00:42:43 +0000 UTC

如何将十进制字符串值转换为数字?

  • 772

有一个包含以下类型数据的文本文件:

    -7.271467826427747 17.84
    -7.238717596285217 17.83
    -7.203784017466519 17.82
    -7.171033787323988 17.81
    -7.138283557181459 17.80
    -7.103349978362760 17.79
    -7.068416399544062 17.78
    -7.033482820725363 17.77
    -6.998549241906665 17.76
    -6.961432314411798 17.75
    -6.924315386916930 17.74
    -6.889381808098232 17.73
    -6.852264880603365 17.72
    -6.812964604432329 17.71
    -6.775847676937462 17.70
    -6.738730749442595 17.69
    -6.699430473271558 17.68
    -6.660130197100525 17.67
    -6.618646572253319 17.66
    -6.577162947406114 17.65
    -6.537862671235079 17.64
    -6.496379046387874 17.63
    -6.452712072864502 17.62
    -6.409045099341129 17.61
    -6.365378125817755 17.60

我正在尝试将此文件转换为数组:

import numpy as np

_overall_survival = open('_overall_survival.txt').read().splitlines()
mas = np.array([line.split() for line in _overall_survival[0:]], float, order='F')

print(mas)

在输出中我们得到:

    [[-39.16145859 81.01]
     [-39.81064093 81.02]
     [-40.02431799 81.03]
     ...
     [-2.39123878 17.24]
     [-2.45739627 17.23]
     [-2.5248678 17.22]]

原则上它是有效的,但float它不能提供小数点后数字传输的准确性,这一点很重要。

我尝试使用Decimal:

from decimal import *
import numpy as np

_overall_survival = open('_overall_survival.txt').read().splitlines()
mas = np.array([line.split() for line in _overall_survival[0:]], Decimal, order='F')

print(mas)

在输出中我们得到:

    [['-39.161458590547106' '81.01']
     ['-39.810640930261251''81.02']
     ['-40.024317987368960''81.03']
     ...
     ['-2.391238778978993''17.24']
     ['-2.457396265486048''17.23']
     ['-2.524867804437093''17.22']]

在这种情况下,数组显示所有小数位,但这是字符串数据,仍然需要以某种方式转换为数字数据。

问题:如何Decimal在保持精度的同时获取数字而不是字符串?

添加:

根据CrazyElf 的Stanislav Volodarskiy的建议,Vitalizzare成功组建了该程序的工作原型。

import tkinter as tk
import numpy as np
from tkinter import ttk

with open('_overall_survival.txt') as f:
    array = np.array([list(map(float, line.split())) for line in f])
    with ((np.printoptions(precision=15))):
        mas = array


# ENGINE
# region
def calc():
    with ((np.printoptions(precision=15))):
        result = float((-0.02144927 * float(entry_a.get())
                        ) + (-0.04948455 * float(entry_b.get())
                             ) + 0.50824824)

        row = mas[np.abs(mas[:, 0] - result).argmin()]
        min_row = float(mas[np.abs(mas[:, 0]).argmin()][0])
        max_row = float(mas[np.abs(mas[:, 0]).argmax()][0])

        if min_row >= result >= max_row:
            score['text'] = mas[np.where(mas == row)][1]
            info['text'] = (f'Расчет: {result}\n'
                            f'ТОЧНОГО СОВПАДЕНИЯ НЕТ!\n'
                            f'Ближайшее значение: '
                            f'{mas[np.where(mas == row)][0]}\n'
                            f'Связанное значение: '
                            f'{mas[np.where(mas == row)][1]}')
        elif result < max_row:
            score['text'] = mas[np.where(mas == row)][1]
            info['text'] = (f'Расчет: {result}\n'
                            f'СОВПАДЕНИЙ НЕТ!\n'
                            f'Расчетное время больше: '
                            f'{mas[np.where(mas == row)][1]}')
        elif result > max_row:
            score['text'] = mas[np.where(mas == row)][1]
            info['text'] = (f'Расчет: {result}\n'
                            f'СОВПАДЕНИЙ НЕТ!\n'
                            f'Расчетное время меньше: '
                            f'{mas[np.where(mas == row)][1]}')
        elif result in mas[:, 0]:
            score['text'] = mas[np.where(mas == row)][1]
            info['text'] = (f'Расчет: {result}\n'
                            f'ЕСТЬ СОВПАДЕНИЕ!\n'
                            f'Связанное значение: '
                            f'{mas[np.where(mas == row)][1]}')


def clear():
    entry_a.delete(0, 'end')
    entry_b.delete(0, 'end')
    # combobox.set('')
    score['text'] = ''
# endregion

# WINDOW
# region
app = tk.Tk()
app.title('FRM CLEAR')
width = 600
height = 350
x = int((app.winfo_screenwidth() / 2) - (width / 2))
y = int((app.winfo_screenheight() / 2) - (height / 2))
app.geometry(f'{width}x{height}+{x}+{y}')
app.resizable(width=False, height=False)
app['background'] = '#3d505a'
# endregion

# RESOURCES
# region
ttk.Style().configure('btn.TButton', background='#56676f')
ttk.Style().configure('frm_app.TFrame', background='#3d505a')
ttk.Style().configure('frm_content.TFrame', background='#56676f')

frm_app = ttk.Frame(app, style='frm_app.TFrame', padding=[20, 20])
frm_app.place(relheight=1, relwidth=1)

frm_content = ttk.Frame(frm_app, style='frm_content.TFrame', padding=[10, 10])
frm_content.place(relheight=0.5, relwidth=1)
# endregion


# UI
# region
entry_a = ttk.Entry(frm_content)
entry_a.place(x=5, y=10, height=25, width=40)

entry_b = ttk.Entry(frm_content)
entry_b.place(x=5, y=45, height=25, width=40)

score = ttk.Label(frm_content, text='', font='Tahoma 20 bold')
score.place(x=235, y=10, height=38, width=300)

info = ttk.Label(frm_content, text='', font='Tahoma 12', 
                 foreground='#ffffff', background='#56676f')
info.place(x=235, y=50, height=77, width=300)

tk.Button(app, text="Calc", command=calc
          ).place(x=470, y=305, height=25, width=50)
tk.Button(app, text="Clear", command=clear
          ).place(x=530, y=305, height=25, width=50)
# endregion
app.mainloop()

至于尝试Decimal,我会做出这个选择,但由于将来那里不会发生太多的计算,而是搜索和与数组内容进行比较,所以不会有任何区别(或者它不会影响比较的结果)。

python
  • 1 1 个回答
  • 48 Views

1 个回答

  • Voted
  1. Best Answer
    Stanislav Volodarskiy
    2025-03-19T01:04:22Z2025-03-19T01:04:22Z

    NumPy 不会打印所有有效数字,需要进行配置:numpy.set_printoptions。

    import numpy as np
    
    with open('temp.txt') as f:
        a = np.array([
            list(map(float, line.split()))
            for line in f
        ])
    
    with np.printoptions(precision=15):
        print(a)
    

    所有数字均已到位:

    $ python np-print.py
    [[-7.271467826427747 17.84             ]
     [-7.238717596285217 17.83             ]
     [-7.203784017466519 17.82             ]
     [-7.171033787323988 17.81             ]
     [-7.138283557181459 17.8              ]]
    

    如果您仍想使用decimal.Decimal,NumPy 可以对其进行操作。虽然速度很慢,但它可以:

    import decimal
    import numpy as np
    
    with open('temp.txt') as f:
        a = np.array([
            list(map(decimal.Decimal, line.split()))
            for line in f
        ])
    
    print(a)
    print(2 * a)
    
    $ python np-decimal.py
    [[Decimal('-7.271467826427747') Decimal('17.84')]
     [Decimal('-7.238717596285217') Decimal('17.83')]
     [Decimal('-7.203784017466519') Decimal('17.82')]
     [Decimal('-7.171033787323988') Decimal('17.81')]
     [Decimal('-7.138283557181459') Decimal('17.80')]]
    [[Decimal('-14.542935652855494') Decimal('35.68')]
     [Decimal('-14.477435192570434') Decimal('35.66')]
     [Decimal('-14.407568034933038') Decimal('35.64')]
     [Decimal('-14.342067574647976') Decimal('35.62')]
     [Decimal('-14.276567114362918') Decimal('35.60')]]
    
    • 3

相关问题

  • 是否可以以某种方式自定义 QTabWidget?

  • telebot.anihelper.ApiException 错误

  • Python。检查一个数字是否是 3 的幂。输出 无

  • 解析多个响应

  • 交换两个数组的元素,以便它们的新内容也反转

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5