如何将一个列表的元素直接放到另一个列表中?

2024-09-27 23:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个字典(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)

谢谢


Tags: name元素列表字典all解决方案scoreprint
3条回答

当您调用All.append(Class1['score'])时,包含在词汇表中的列表将被视为单个元素,并作为一个整体添加到All列表中。你知道吗

你要么像以前那样循环遍历列表中的每一项,要么使用list.extend方法,它将把你的列表与另一个迭代器合并,即将另一个迭代器中的每一项附加到你的起始列表中。你知道吗

您可以使用extend

extend(...)

L.extend(iterable) -- extend list by appending elements from the iterable
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)

你知道吗全部。扩展(…)会做你想做的事。。。你知道吗

相关问题 更多 >

    热门问题