python数组反转_反转Python中元组列表中的每个元组

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数组反转

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值