python数组反转
Tuples in Python are a collection of elements in a round bracket() or not but separated by commas. Tuples are similar to list in some operations like indexing, concatenation, etc. but lists are mutable whereas tuples are immutable acts like a string. Here, a list of tuples will be given by the user and we have to reverse each tuple in Python.
Python中的元组是圆括号()中元素的集合,不是,而是用逗号分隔。 元组在某些操作(例如索引,连接等)中类似于列表,但是列表是可变的,而元组是不可变的行为,例如字符串。 在这里,用户将给出一个元组列表,我们必须在Python中反转每个元组 。
For example, list of tuple A=[(9,0), (2,5), (4,6), (7,1), (1,5)] is given by the user and we have to return it like [(0,9), (5,2), (6,4), (1,7), (5,1)] which have reverse of each tuples of list.
例如 , 元组A = [(9,0),(2,5),(4,6),(7,1),(1,5)]的列表由用户给出,我们必须返回它像[(0,9),(5,2),(6,4),(1,7),(5,1)] ,它们具有列表中每个元组的倒序。
We are going to solve this problem with two approaches, the first one is by using the slicing property and another one is by using the predefined reversed() function of Python language. So, let's start simply writing the program.
我们将通过两种方法解决此问题,第一种方法是使用slicing属性,另一种方法是使用Python语言的预定义的reversed()函数 。 因此,让我们开始简单地编写程序。
1)通过使用切片属性 (1) By using the slicing property)
#suppose a list of tuples provided by the user is A.
A=[(4,5), (4,6), (6,9), (3,6),(12,0), (6,7)]
B=[k[::-1] for k in A]
print('List of reversed tuples:',B)
Output
输出量
List of reversed tuples: [(5, 4), (6, 4), (9, 6), (6, 3), (0, 12), (7, 6)]
In Python, [::-1] used to reversed list, string, etc.
在Python中, [::-1]用于反转列表,字符串等。
2)通过使用Python的反向功能 (2) By using the reversed function of Python)
The reversed() function used to reverse a list, string, etc. in Python. It acts like the above slicing property.
reversed()函数用于在Python中反转列表,字符串等。 它的作用类似于上述切片属性。
#suppose the same input of the above program.
A=[(4,5), (4,6), (6,9), (3,6),(12,0), (6,7)]
B=[tuple(reversed(k)) for k in A]
print('List of reversed tuples:',B)
Output
输出量
List of reversed tuples: [(5, 4), (6, 4), (9, 6), (6, 3), (0, 12), (7, 6)]
翻译自: https://www.includehelp.com/python/reverse-each-tuple-in-a-list-of-tuples.aspx
python数组反转