Reversing/Sort 在打印语句中
Reversing/Sort in a print statement
我正在尝试对 list2
的打印输出进行排序。
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2 + list1 + list2.sort(reverse=True)
print(f"The new list is: {list3}")
我正在尝试为 list3
创建一个仅使用 list1
和 list2
的单个 Python 语句来构造一个新的 list3
,以便该代码将打印以下输出 运行.
The new list is: [40, 50, 60, 1, 2, 3, 60, 50, 40]
但是,我收到一个错误:
TypeError: can only concatenate list (not "NoneType") to list
编辑:将 list2.sort(reverse.True)
更改为 list2.sort(reverse=True)
list3 = list2 + list1 + list2.sort(reverse.True)
抛出 Syntax Error
- 你的意思可能是:list3 = list2 + list1 + list2.sort(reverse = True)
.
[提示] 比 list2.sort(reverse = True)
更简单的方法是 list2.reverse()
。
但是,(list2.sort(reverse = True)
和 list2.reverse()
)都是 in-place 操作 - 它们不是列表对象,只是更改列表的操作。
为了能够对列表求和,您必须添加列表对象,例如:list2[::-1]
:
list3 = list2 + list1 + list2[::-1]
由于 list2.sort(reverse.True)
原地排序 list2
并且 returns None
您不能将其连接到 list2 + list1
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2 + list1 + sorted(list2, reverse=True)
print(f"The new list is: {list3}")
使用 sorted
工作,其中 returns 排序列表
In-place 排序:
list1 = [2, 3, 1]
list1.sort()
print(list1)
>> [1, 2, 3]
Out-of-Place 排序:
list1 = [2, 3, 1]
result_list = sorted(list1)
print(list1)
>> [2, 3, 1]
print(result_list)
>> [1, 2, 3]
查看 https://docs.python.org/3/howto/sorting.html 了解更多信息。它给出了一个简短的介绍。
试试这个
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2.copy()
list3.sort(reverse=True)
list4 = list2 + list1 + list3
print(f"The new list is: {list4}")
我正在尝试对 list2
的打印输出进行排序。
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2 + list1 + list2.sort(reverse=True)
print(f"The new list is: {list3}")
我正在尝试为 list3
创建一个仅使用 list1
和 list2
的单个 Python 语句来构造一个新的 list3
,以便该代码将打印以下输出 运行.
The new list is: [40, 50, 60, 1, 2, 3, 60, 50, 40]
但是,我收到一个错误:
TypeError: can only concatenate list (not "NoneType") to list
编辑:将 list2.sort(reverse.True)
更改为 list2.sort(reverse=True)
list3 = list2 + list1 + list2.sort(reverse.True)
抛出 Syntax Error
- 你的意思可能是:list3 = list2 + list1 + list2.sort(reverse = True)
.
[提示] 比 list2.sort(reverse = True)
更简单的方法是 list2.reverse()
。
但是,(list2.sort(reverse = True)
和 list2.reverse()
)都是 in-place 操作 - 它们不是列表对象,只是更改列表的操作。
为了能够对列表求和,您必须添加列表对象,例如:list2[::-1]
:
list3 = list2 + list1 + list2[::-1]
由于 list2.sort(reverse.True)
原地排序 list2
并且 returns None
您不能将其连接到 list2 + list1
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2 + list1 + sorted(list2, reverse=True)
print(f"The new list is: {list3}")
使用 sorted
工作,其中 returns 排序列表
In-place 排序:
list1 = [2, 3, 1]
list1.sort()
print(list1)
>> [1, 2, 3]
Out-of-Place 排序:
list1 = [2, 3, 1]
result_list = sorted(list1)
print(list1)
>> [2, 3, 1]
print(result_list)
>> [1, 2, 3]
查看 https://docs.python.org/3/howto/sorting.html 了解更多信息。它给出了一个简短的介绍。
试试这个
list1 = [1, 2, 3]
list2 = [40, 50, 60]
list3 = list2.copy()
list3.sort(reverse=True)
list4 = list2 + list1 + list3
print(f"The new list is: {list4}")