Python列表reverse()
时间:2020-02-23 14:42:56 来源:igfitidea点击:
在本教程中,我们将看到Python列表的reverse方法。
Python列表reverse方法用于反转列表。
Python列表反转示例
我们可以简单地调用反向方法以反转列表。
让我们在简单的例子的帮助下了解这一点。
listOfItems=['Clock','Bed','Fan','Table'] print("listOfItems:",listOfItems) listOfItems.reverse() print("listOfItems in reversed order:",listOfItems)
输出:
listOfItems: ['Clock', 'Bed', 'Fan', 'Table'] listOfItems in reversed order: ['Table', 'Fan', 'Bed', 'Clock']
我们可以在此处看到,列表使用反向方法反转。
还有其他方法可以反转列表。
我们可以使用SliCing来反转列表。
listOfItems=['Clock','Bed','Fan','Table'] print("listOfItems:",listOfItems) listOfItems=listOfItems[::-1] print("listOfItems in reversed order:",listOfItems)
输出:
listOfItems: ['Clock', 'Bed', 'Fan', 'Table'] listOfItems in reversed order: ['Table', 'Fan', 'Bed', 'Clock']
如果我们只想以相反的顺序遍历,我们也可以使用反转函数。
listOfItems=['Clock','Bed','Fan','Table'] for item in reversed(listOfItems): print(item)
输出:
Table Fan Bed Clock