Python 程序合并两个列表并对它们排序


当需要合并两个列表并对它们排序时,可以使用一种方法,该方法使用“sort”方法对列表进行排序。

下面是对它的演示 −

示例

 现场演示

def merge_list(list_1, list_2):
   merged_list = list_1 + list_2
   merged_list.sort()
   return(merged_list)

list_1 = [20, 18, 9, 51, 48, 31]
list_2 = [28, 33, 3, 22, 15, 20]
print("The first list is :")
print(list_1)
print("The second list is :")
print(list_2)
print(merge_list(list_1, list_2))

输出

The first list is :
[20, 18, 9, 51, 48, 31]
The second list is :
[28, 33, 3, 22, 15, 20]
[3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]

说明

  • 定义一个名为“merge_list”的方法,将两个列表作为参数。

  • 使用“+”运算符连接两个列表。

  • 参数被赋给一个变量。

  • 使用 sort 方法对最终结果进行排序。

  • 在方法之外,定义两个列表,并显示在控制台上。

  • 通过传递这两个列表来调用该方法。

  • 输出显示在控制台上。

更新于: 2021 年 4 月 19 日

2K+ 浏览量

开启您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.