How to put the element of a list to another list directly?
我有几个字典(
我尝试以下代码
1 2 3 4 5 6 | All = [] Class1 = {"name":"A","score":[60,70,80]} Class2 = {"naem":"B","score":[70,80,90]} All.append(Class1['score']) All.append(Class2['score']) print(All) |
但结果是
1 | [[60, 70, 80], [70, 80, 90]] |
号
但我想要的是
1 | [60, 70, 80, 70, 80, 90] |
我尝试下面的解决方案,但我想知道是否存在更好的解决方案?
1 2 3 4 5 6 7 8 9 10 11 12 | All = [] Class1 = {"name":"A","score":[60,70,80]} Class2 = {"naem":"B","score":[70,80,90]} Scores1 = Class1['score'] Scores2 = Class2['score'] Scores = Scores1 + Scores2 for score in Scores: All.append(score) print(All) |
。
谢谢
您可以使用
1
2
3 extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
号
1 2 3 4 5 6 | All = [] Class1 = {"name":"A","score":[60,70,80]} Class2 = {"naem":"B","score":[70,80,90]} All.extend(Class1['score']) All.extend(Class2['score']) print(All) |
如果
1 | All.extend(Class1["score"] + Class2["score"]) |
。
调用
您要么像以前那样循环遍历列表中的每个项,要么使用
1 | All = Class1["score"] + Class2["score"] |
号
以后添加更多元素:
1 | ALL += Classx["score"] |
全部。扩展(…)将执行您想要的操作…