gpt4 book ai didi

javascript - 将数组从 python 传输到 javascript

转载 作者:行者123 更新时间:2023-11-28 21:11:25 25 4
gpt4 key购买 nike

我有一个包含两列数据(x 和 y)的 test.txt 文件,例如:

#test.txt
1 23
2 234
4 52
43 5
3 35

还有一个 python 程序读取这些值并将它们存储在 x 和 y 中:

#test.py
# Read the file.
f = open('test.txt', 'r')

# read the whole file into a single variable, which is a list of every row of the file.
lines = f.readlines()
f.close()

# initialize some variable to be lists:
x = []
y = []

# scan the rows of the file stored in lines, and put the values into some variables:
for line in lines:
p = line.split()
x.append(float(p[0]))
y.append(float(p[1]))

我想获取存储在 x 和 y 中的这些值,并将它们传输到 javascript 程序中的两个相似数组,以将它们显示为图形。如何在 python 和 javascript 之间转换?

最佳答案

你的问题有点含糊。您的问题有两种可能的解释方式,以下是相应的答案:

  1. 您的 python 代码需要将它们传输到在浏览器/node.js 应用程序中运行的一些 javascript。为了做到这一点,应用程序的 Python 部分需要将数据存储在数据库中并通过某种 API 公开数据,JavaScript 部分可以使用这些 API。更有趣的是,您可以在两个 Web 服务器(例如 socket.io)之间建立连接,并让 Python 一半在创建数组时通过连接发送数组。
  2. 根据您发布的代码,我认为这就是您尝试做的事情:在 Python 中预处理一些数据,然后将其传递给其他一些 javascript 拼图,其中没有真正-时间方面。

    在这种情况下,您可以简单地将数组写入 JSON,然后用 Javascript 对其进行解析。要写入文件,您可以执行以下操作:

    import json
    data = {'x': x, 'y': y}
    # To write to a file:
    with open("output.json", "w") as f:
    json.dump(data, f)

    # To print out the JSON string (which you could then hardcode into the JS)
    json.dumps(data)

关于javascript - 将数组从 python 传输到 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35394788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com