我正在尝试将一些代码从 Python 移植到 C#。
目标是比较相邻元素并查看四个连续值是否大于彼此。
在这篇文章( Compare two adjacent elements in same list )之后,我能够在双端队列上使用pairwise来成功地比较相邻元素。
//In python
from more_itertools import pairwise
for x, y in pairwise(a_deque):
if (x < y):
i += 1
if (i == 4)
print("Hello world!")
问题是 C# 不包含 more_itertools 库,因此我目前正在寻找类似的技术来实现相同的解决方案。
仅供引用。双端队列实现来自https://www.nuget.org/packages/Nito.Collections.Deque/
有什么建议吗?
最佳答案
您可以像这样自己实现 python 成对方法:
public static IEnumerable<(T, T)> Pairwise<T>(IEnumerable<T> collection)
{
using (var enumerator = collection.GetEnumerator())
{
enumerator.MoveNext();
var previous = enumerator.Current;
while (enumerator.MoveNext())
{
yield return (previous, enumerator.Current);
previous = enumerator.Current;
}
}
}
那么c#中的算法在结构上与python版本非常相似:
static void Main(string[] args)
{
var values = new[] { 5, 7, 8, 9, 10, 10, 8, 2, 1 };
var i = 0;
foreach (var (x, y) in Pairwise(values))
{
if (x < y)
{
i++;
if (i == 4)
Console.WriteLine("Hello world!");
}
}
Console.ReadLine();
}
关于c# - 如何在 C# 中比较相邻的双端队列元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58183103/