如何在Python3中将元素从一个列表添加到另一个列表?
我有两份清单:如何在Python3中将元素从一个列表添加到另一个列表?,python,python-3.x,list,Python,Python 3.x,List,我有两份清单: list_1 = [100,100,50,40,40,20,10] list_2 = [5,25,50,120] 我想在嵌套列表中按降序将数字/元素从列表_2移动到列表_1: [[100,100,50,40,40,20,10,5],[100,100,50,40,40,25,20,10],[100,100,50,50,40,40,20,10],[120,100,100,50,40,40,20,10]] 如何使用Python 3实现这一点?查找以下代码: list_1 = [10
list_1 = [100,100,50,40,40,20,10]
list_2 = [5,25,50,120]
我想在嵌套列表中按降序将数字/元素从列表_2移动到列表_1:
[[100,100,50,40,40,20,10,5],[100,100,50,40,40,25,20,10],[100,100,50,50,40,40,20,10],[120,100,100,50,40,40,20,10]]
如何使用Python 3实现这一点?查找以下代码:
list_1 = [100, 100, 50, 40, 40, 20, 10]
list_2 = [5, 25, 50, 120]
final_list = []
for l1 in list_2:
temp_list_1 = list_1.copy()
temp_list_1.append(l1)
temp_list_1.sort(reverse=True)
final_list.append(temp_list_1)
print(final_list)
说明:
循环列表2的元素并将其附加到临时列表1上。然后按降序排序。最后,将排序后的列表附加到新的最终列表上。您可以在此处尝试列表理解:
main_list = [sorted(list_1+[i], reverse=True) for i in list_2]
print(main_list)
在这里,我将每个元素添加到列表_1中,然后按降序排序到主列表中
O/p将类似于:
[[100, 100, 50, 40, 40, 20, 10, 5], [100, 100, 50, 40, 40, 25, 20, 10],
[100, 100, 50, 50, 40, 40, 20, 10], [120, 100, 100, 50, 40, 40, 20, 10]]
[[100, 100, 50, 40, 40, 20, 10, 5], [100, 100, 50, 40, 40, 25, 20, 10],
[100, 100, 50, 50, 40, 40, 20, 10], [120, 100, 100, 50, 40, 40, 20, 10]]