![](/img/trans.png)
[英]Python, how to randomly add/append elements from one list to another?
[英]How to add the elements from one list to another list in Python3?
我有两个清单:
list_1 = [100,100,50,40,40,20,10]
list_2 = [5,25,50,120]
我想在嵌套列表中以降序将数字/元素从list_2移动到list_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)
说明:
遍历list_2的元素并将其附加到temp_list_1 。 然后按降序排序。 最后将排序列表附加到新的final_list上 。
list_1 = [100,100,50,40,40,20,10]
list_2 = [5,25,50,120]
lst = [sorted(list_1 + [list_2[i]], reverse=True) for i in range(len(list_2))]
print(lst)
你可以在这里尝试列表理解:
main_list = [sorted(list_1+[i], reverse=True) for i in list_2]
print(main_list)
在这里,我将每个元素添加到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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.