1

在烧瓶应用程序中创建的图表中。我必须遍历字典和列表。我现在有这个。

series:
                    [{
                            points: [
                            
                            {% for key, value in Top10.items() %}
                                {% for color in colors%}
                                       { x: "{{key}}", y: {{ value }}, fill = "{{ color }}" }, //"" as it is a string
                                    {% endfor %}
                                {% endfor %}
                            ]                 
                    }],

前 10 名 = {"a":10,"b":15,"c":5,"d":8,"e":4,..} 和颜色 = ["blue", "black", "红色的”...]

当前输出:{ x: "a", y: 10, fill = "blue" }, { x: "a", y: 10, fill = "black" }, ....

循环的预期输出是:{ x: "a", y: 10, fill = "blue" }, { x: "b", y: 15, fill = "black" },....

4

3 回答 3

2

您可以使用 zip 和 iteritems() 压缩字典和列表。并通过压缩列表循环。

Top10 = {"a":10,"b":15,"c":5,"d":8,"e":4}
Colors = ["blue", "black", "red"]
Zipped = zip(Top10.iteritems(), Colors)

for (key, value), color in Zipped:
    print(key,value,color)
于 2021-07-02T07:19:39.980 回答
2

根据您的预期输出,您真的不希望在 Top10 项目中嵌套 for 循环颜色。似乎您想要 Top10 项目与颜色的一对一映射。如果是这种情况,@Sefan 在答案中给出了一些线索。在这里,我可以用 Flask 和 Jinja 的方式给你完整的例子。

在您看来,假设app.py您可以压缩两个数据对象,如下所示:

@app.route('/breakloop')
def breakloop():
    Top10 =  {"a":10,"b":15,"c":5,"d":8,"e":4}
    colors = ["blue", "black", "red"]

    return render_template('breakloop.html', zipped=zip(Top10.items(), colors))

在您的模板中,假设breakloop.html

{% for (key, value), color in zipped %}
        { x: "{{key}}", y: {{ value }}, fill = "{{ color }}" }, </br> 
{% endfor %}

结果:

{ x: "a", y: 10, fill = "blue" }, 
{ x: "b", y: 15, fill = "black" }, 
{ x: "c", y: 5, fill = "red" }, 
于 2021-07-02T09:02:51.257 回答
0

我们已根据您的要求准备了样品。在这方面,我们根据您的要求创建了数据。

  public top10: Object = { a: 10, b: 15, c: 5, d: 8, e: 4 };
  public colors: string[] = ['blue', 'black', 'red', 'yellow', 'green'];
  public data: Object[] = this.getData();
  public getData(): Object[] {
    let count = 0;
    let currentData: Object[] = [];
    for (const [key, value] of Object.entries(this.top10)) {
      currentData.push({
        x: `${key}`,
        y: `${value}`,
        fill: this.colors[count++]
      });
    }
    count = 0;
    return currentData;
  }
<ejs-chart>
    <e-series-collection>
       <e-series [dataSource]='data' xName='x' yName='y' pointColorMapping="fill">
       </e-series>
     </e-series-collection>
</ejs-chart>

示例链接:https ://stackblitz.com/edit/angular-tjjts9?file=app.component.html

于 2021-07-05T12:31:02.430 回答