根据嵌套列表的索引将元素追加到嵌套列表中

时间:2020-01-28 11:49:22

标签: python list

我有一个看起来像这样的嵌套列表:

l = [[['0.056*"googl"'], ['0.035*"facebook"']], #Index 0
    [['0.021*"mensch"'], ['0.012*"forsch"']], #Index 1
    [['0.112*"appl"'], ['0.029*"app"']], # Index 2
    [['0.015*"intel"'], ['0.015*"usb"']]] #Index 3

现在,我想将子列表的索引(和主题词)附加到单个子列表中,如下所示:

nl = [[['0.056*"googl"', 'Topic 0'], ['0.035*"facebook"', 'Topic 0']], 
     [['0.021*"mensch"', 'Topic 1'], ['0.012*"forsch"', 'Topic 1']], 
     [['0.112*"appl"', 'Topic 2'], ['0.029*"app"', 'Topic 2']], 
     [['0.015*"intel"', 'Topic 3'], ['0.015*"usb"', 'Topic 3']]]

我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用:

nl = [[[*x, 'Topic %s' % idx] for x in i] for idx, i in enumerate(l)]

或使用:

nl = [[x + ['Topic %s' % idx] for x in i] for idx, i in enumerate(l)]

现在:

print(nl)

是:

[[['0.056*"googl"', 'Topic 0'], [' 0.035*"facebook"', 'Topic 0']], [['0.021*"mensch"', 'Topic 1'], [' 0.012*"forsch"', 'Topic 1']], [['0.112*"appl"', 'Topic 2'], [' 0.029*"app"', 'Topic 2']], [['0.015*"intel"', 'Topic 3'], [' 0.015*"usb"', 'Topic 3']]]

答案 1 :(得分:1)

您可以使用 const pieData: Array<number> = [3, 4, 5, 6, 7]; export class AppComponent { height = 500; width = 500; transform = `translate(${this.width / 2}, ${this.height / 2})`; color = d3 .scaleOrdinal() .domain(["1", "2", "3", "4", "5"]) .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]); arcData = d3.pie()(pieData); final; ngAfterViewInit() { this.final = this.arcData.map(d => { return d3 .arc() .startAngle(+d.startAngle) .endAngle(+d.endAngle) .innerRadius(50) .outerRadius(100)(this.arcData); }); const final2 = this.arcData.map(d => { return d3 .arc() .startAngle(+d.startAngle) .endAngle(+d.endAngle) .innerRadius(100) // type error on (this.arcData) .outerRadius(150) (this.arcData); }); this.final = this.final.concat(final2); console.log(this.final); } } 循环

for
相关问题