读取 2 个列表并从以相反顺序组合的列表中打印数字的程序

Program to read 2 lists and print numbers from lists combined in reverse order

您好,我一直在编写一个程序,用户可以在其中为两个不同的列表输入数字,该程序会打印组合的列表并以相反的顺序(最高 - 最低)对数字进行排序。

我已经设法编写了一个程序,但我需要一种方法来更改它,以便用户在一行而不是多行中输入列表,然后我的最终结果不会打印在(最高 - 最低)它目前仅打印(低-高)

看下面我的代码

a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
    b=int(input("Enter element:"))
    a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
    d=int(input("Enter element:"))
    c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)

输出

Enter number of elements:4
Enter element:1
Enter element:3
Enter element:3
Enter element:6
Enter number of elements:3
Enter element:1
Enter element:4
Enter element:5
Sorted list is: [1, 1, 3, 3, 4, 5, 6]

我怎样才能更改我的代码,使其看起来像这样:

list 1 : 1 2 3 4
list 2 : 5 6 7 8
output :[ 8,7,6,5,4,3,2,1]

要在一行中输入列表,请执行以下操作

a = [int(i) for i in input("list 1: ").split(" ")]

正如 Albin Paul 在评论中指出的那样,使用

new.sort(reverse=True)

从高到低排序

1.if 您想要反转排序数组,您可以在下面使用:

new.sort(reverse=True)
  1. 如果您只想反转列表,您可以使用:
new[::-1]#will give you a reverse list

#or else you can use predefined method 
new.reverse()

这行得通。您也可以要求以逗号分隔输入。

每个列表的示例输入如下所示: 1 2 3 4 5

lst1 = input("Enter list of space separated numbers:") # input = `2 1 4 7 5 9`
lst2 = input("Enter list of space separated numbers:")
a = [int(i) for i in lst1.split(' ') if i.isdigit()]
c = [int(i) for i in lst2.split(' ') if i.isdigit()]

new= a + c
new.sort(reverse=True)
print("Sorted list is:",new)

您可以将两个列表放在一行中并用空格分隔。并将它们转换为int,合并它们并按降序排列。

list1 = input('Enter List 1:  ')
list2 = input('Enter List 2:  ')
list_1 = list1.split()
list_2 = list2.split()
# print list

list_1 = list(map(int, list_1))
list_2 = list(map(int, list_2))

final_list = list_1 + list_2


# 1
print(sorted(final_list, reverse=True))

# 2
final_list.sort(reverse=True)
print(final_list)```