简体   繁体   English

将两个列表转换为 X 和 Y 格式的字典

[英]Convert two lists into a dictionary of X and Y Format

I have two lists containing around 300 decimal numbers.我有两个包含大约 300 个十进制数字的列表。 That I need to convert into a dictionary format like below in order to plot a scatter graph using the values within the two lists as X and Y coordinates with Chart.JS.我需要转换为如下所示的字典格式,以便 plot 使用两个列表中的值作为 Chart.JS 的 X 和 Y 坐标的散点图。

This is the format that Chart.JS requires the data to be in.这是 Chart.JS 要求数据采用的格式。

           data: [{
               x: -10,
               y: 0
           }, {
               x: 0,
               y: 10
           }, {
               x: 10,
               y: 5
           }]

I've been trying to do this in a number of different ways but each time I get it wrong.我一直在尝试以多种不同的方式做到这一点,但每次我都弄错了。 Does anyone know a good way to accomplish this?有谁知道实现这一目标的好方法?

You can use Array#map to generate such an array.您可以使用Array#map来生成这样的数组。

The second parameter of the map function is the index, you can get the y value by that index. map function 的第二个参数是索引,通过该索引可以得到y值。

 const features = [1, 2, 3, 4, 5, 6]; const labels = [11, 22, 33, 44, 55, 66]; const coords = features.map((x, i) => ({ x, y: labels[i] })); console.log(coords);

Someone has already written the Javascript solution, I will describe Python way.有人已经写了Javascript的解决方案,我将描述Python的方式。

a = [1, 2, 3, 4, 5];
b = [9, 8, 7, 6, 5];

data = []

for x, y in zip(a, b):
    data.append({'x': x, 'y': y})

or shorter and pythonic style:或更短的pythonic风格:

data = [{'x': x, 'y': y} for x, y in zip(a, b)]

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

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