繁体   English   中英

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

[英]How to reverse certain tuple (user input by index of the list) in a list in 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

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

使用内置的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 = [j[::-1] if i in b else j for i,j in enumerate(a)]

您可以使用列表切片。

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:]

打印(输出)

[(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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM