在本教程中,我们将编写一个程序,该程序合并两个列表并按排序顺序打印结果列表。让我们看一些例子。
Input: list_1 = [1, 3, 2, 0, 3] list_2 = [20, 10, 23, 43, 56, -1] Output: [-1, 0, 1, 2, 3, 3, 10, 20, 23, 43, 56]
Input: list_1 = ["hafeez", "aslan"] list_2 = ["abc", "kareem", "b"] Output: ["abc", "aslan", "b", "hafeez", "kareem"]
让我们尝试通过以下步骤编写代码。
1. Initialize the lists. 2. Concatenate the two lists using + operator and store the result in a new variable. 3. Sort the resultant list with sort() method of the list. 4. Print the sorted list.
参见代码。
## initializing the lists list_1 = [1, 3, 2, 0, 3] list_2 = [20, 10, 23, 43, 56, -1] ## concatenating two lists new_list = list_1 + list_2 ## soring the new_list with sort() method new_list.sort() ## printing the sorted list print(new_list)
输出结果
如果运行上述程序,将得到以下输出。
[-1, 0, 1, 2, 3, 3, 10, 20, 23, 43, 56]
我们正在执行具有不同列表的同一程序。
## initializing the lists list_1 = ["hafeez", "aslan"] list_2 = ["abc", "kareem", "b"] ## concatenating two lists new_list = list_1 + list_2 ## soring the new_list with sort() method new_list.sort() ## printing the sorted list print(new_list)
输出结果
如果运行上述程序,将得到以下输出。
['abc', 'aslan', 'b', 'hafeez', 'kareem']