[英]How to select increasing elements of a list of tuples?
I have the following list of tuples: 我有以下元组列表:
a = [(1, 2), (2, 4), (3, 1), (4, 4), (5, 2), (6, 8), (7, -1)]
I would like to select the elements which second value in the tuple is increasing compared to the previous one. 我想选择元组中第二个值与前一个元素相比增加的元素。 For example I would select
(2, 4)
because 4
is superior to 2
, in the same manner I would select (4, 4)
and (6, 8)
. 例如,我会选择
(2, 4)
因为4
优于2
,与我选择(4, 4)
和(6, 8)
。
Can this be done in a more elegant way than a loop starting explicitly on the second element ? 这可以以比第二个元素明确开始的循环更优雅的方式完成吗?
To clarify, I want to select the tuples which second elements are superior to the second element of the prior tuple. 为了澄清,我想选择第二个元素优于前一个元组的第二个元素的元组。
You can use a list comprehension to do this fairly easily: 您可以使用列表推导相当容易地执行此操作:
a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i-1][1]]
This uses range(1, len(a))
to start from the second element in the list, then compares the second value in each tuple with the second value from the preceding tuple to determine whether it should be in the new list. 这使用
range(1, len(a))
从列表中的第二个元素开始,然后将每个元组中的第二个值与前一个元组中的第二个值进行比较,以确定它是否应该在新列表中。
Alternatively, you could use zip
to generate pairs of neighbouring tuples: 或者,您可以使用
zip
生成成对的邻近元组:
a = [two for one, two in zip(a, a[1:]) if two[1] > one[1]]
您可以使用enumerate
来派生索引,然后进行列表理解:
a = [t[1] for t in enumerate(a[1:]) if t[1][1] > a[t[0]-1][1]]
You can use list comprehension 您可以使用列表理解
[i for i in a if (i[0] < i[1])]
Returns 返回
[(1, 2), (2, 4), (6, 8)]
Edit: I was incorrect in my understanding of the question. 编辑:我对这个问题的理解不正确。 The above code will return all tuples in which the second element is greater than the first.
上面的代码将返回第二个元素大于第一个元素的所有元组。 This is not the answer to the question OP asked.
这不是OP问的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.