如何在Python中反转列表中的特定元组(用户通过列表索引输入)?

2024-05-31 23:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在列表中有元组:

  a=[(1.51, 0.0), (0.93, 0.0), (0.57, 0.0), (0.35, 0.0), (166.0, 0.0), (5.92, 0.0), (15.36, 0.0), (9.89, 0.0), (30.2, 0.0), (5.2, 0.0), (13.31, 0.82)]

现在,用户将列表的索引作为一个列表作为输入,我只想在该索引处反转元组

#b=Input the index positions as list
b=[7,10] # positions at which to reverse the tuple

对于这个exmaple,我只想反转索引7和10处的元组。 最有效的方法是什么?我所能想到的就是2个嵌套for循环,这是非常低效的


Tags: theto用户which列表inputindexas
3条回答

我想你需要

 a = [j[::-1] if i in b else j for i,j in enumerate(a)]

使用内置的reversed

a = [(1.51, 0.0), (0.93, 0.0), (0.57, 0.0), (0.35, 0.0), (166.0, 0.0), (5.92, 0.0), (15.36, 0.0), (9.89, 0.0), (30.2, 0.0), (5.2, 0.0), (13.31, 0.82)]
b = [7,10]
for index in b:
    a[index] = tuple(reversed(a[index]))

您可以使用列表切片

a=[(1.51, 0.0), (0.93, 0.0), (0.57, 0.0), (0.35, 0.0), (166.0, 0.0), (5.92, 0.0), (15.36, 0.0), (9.89, 0.0), (30.2, 0.0), (5.2, 0.0), (13.31, 0.82)]

output = a[:b[0]] + a[b[1]:b[0]:-1] + a[b[1]+1:]

print(output)

[(1.51, 0.0), (0.93, 0.0), (0.57, 0.0), (0.35, 0.0), (166.0, 0.0), (5.92, 0.0), (15.36, 0.0), (13.31, 0.82), (5.2, 0.0), (30.2, 0.0)]

相关问题 更多 >