我有几个字典(Class1 , Class2
),字典的一个元素存储一个列表(Score
),我想把列表的元素放到另一个列表中,而不是把列表本身放到另一个列表中。你知道吗
我尝试以下代码
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)
但结果是
[[60, 70, 80], [70, 80, 90]]
但我想要的是
[60, 70, 80, 70, 80, 90]
我在下面尝试这个解决方案,但我想知道有没有更好的解决方案?你知道吗
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)
谢谢
当您调用
All.append(Class1['score'])
时,包含在词汇表中的列表将被视为单个元素,并作为一个整体添加到All
列表中。你知道吗你要么像以前那样循环遍历列表中的每一项,要么使用
list.extend
方法,它将把你的列表与另一个迭代器合并,即将另一个迭代器中的每一项附加到你的起始列表中。你知道吗您可以使用
extend
:你知道吗全部。扩展(…)会做你想做的事。。。你知道吗
相关问题 更多 >
编程相关推荐