问题描述
我正在使用python,并且正在将代码实现为c#,并且在python中有方法"product",有人知道c#中是否存在类似的东西?如果不是,也许有人可以让我了解如何自己编写此功能?
I am working with python, and I am implementing my code to c# and in python there is method "product", anyone knows if there is something similar in c#? if not maybe someone can put me on a track of how to write this function by myself?
产品示例:
a=[[[(1, 2), (3, 4)], [(5, 6), (7, 8)], [(9, 10), (11, 12)]], [[(13, 14), (15, 16)]]]
b= product(*a)
输出:
([(1, 2), (3, 4)], [(13, 14), (15, 16)])
([(5, 6), (7, 8)], [(13, 14), (15, 16)])
([(9, 10), (11, 12)], [(13, 14), (15, 16)])
推荐答案
假设您的意思是 itertools.product (看起来像给定的示例):
Assuming you mean itertools.product (it looks like it from the example given):
public static List< Tuple<T, T> > Product<T>(List<T> a, List<T> b)
where T : struct
{
List<Tuple<T, T>> result = new List<Tuple<T, T>>();
foreach(T t1 in a)
{
foreach(T t2 in b)
result.Add(Tuple.Create<T, T>(t1, t2));
}
return result;
}
n.b. struct
在这里意味着T
必须是值类型或结构.如果需要抛出诸如List
之类的对象,但要注意潜在的引用问题,请将其更改为class
.
n.b. struct
here means that T
must be a value type or a structure. Change it to class
if you need to throw in objects such as List
s, but be aware of potential referencing issues.
然后作为驱动程序:
List<int> listA = new List<int>() { 1, 2, 3 };
List<int> listB = new List<int>() { 7, 8, 9 };
List<Tuple<int, int>> product = Product<int>(listA, listB);
foreach (Tuple<int, int> tuple in product)
Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);
输出:
1, 7
1, 8
1, 9
2, 7
2, 8
2, 9
3, 7
3, 8
3, 9
这篇关于C#中的乘积方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!