python - 如何将元素从一个列表添加到 Python3 中的另一个列表?

标签 python python-3.x list

我有两个列表:

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

关于python - 如何将元素从一个列表添加到 Python3 中的另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403632/

相关文章:

python - 如何从socket.timeout错误中恢复是selenium(python)

python - 谁能解释为什么 True, True == (True, True) 的输出是 (True, False)?

python - Sorted(items, lambda) 具有多个项目,其中一个相反

python - 当 n 大于列表中元素的数量时,将列表旋转 n 次

python - 不区分大小写的翻译

python - 如何访问生成器提供的 Keras 自定义损失函数中的样本权重?

python - 为什么我只能在异步函数中使用await关键字?

python - "AttributeError: ' float ' object has no attribute ' 替换 '"安装 python 包时出错

python - python 中 all() 的行为

list - 如何从列表中删除第一个元素?