C#中的乘积方法

我正在使用python,并且正在将代码实现为c#,并且在python中有方法“ product”,有人知道c#中是否存在类似的东西?如果不是,也许有人可以让我了解如何自己编写此功能?


产品示例:


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


潇湘沐
浏览 359回答 3
3回答

慕婉清6462132

假设您的意思是itertools.product(看起来像给定的示例):public static List< Tuple<T, T> > Product<T>(List<T> a, List<T> b)&nbsp; &nbsp; where T : struct{&nbsp; &nbsp; List<Tuple<T, T>> result = new List<Tuple<T, T>>();&nbsp; &nbsp; foreach(T t1 in a)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; foreach(T t2 in b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.Add(Tuple.Create<T, T>(t1, t2));&nbsp; &nbsp; }&nbsp; &nbsp; return result;}nbstruct在这里意味着T必须是值类型或结构。class如果您需要抛出Lists之类的对象,但是要注意潜在的引用问题,请将其更改为。然后作为驱动程序: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)&nbsp; &nbsp; Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);输出:1, 71, 81, 92, 72, 82, 93, 73, 83, 9

互换的青春

对于超过列表数量有效的产品功能,您可以在此处使用我的CrossProductFunction.CrossProduct代码:List<List<Tuple<int>>> a = new List<List<Tuple<int>>> { /*....*/ }IEnumerable<List<Tuple<int>>> b = CrossProductFunctions.CrossProduct(a)当前,它不接受repeat参数itertools.product,但是在功能和设计上相似。

qq_笑_17

&nbsp; 这是用c#编写函数的语法:public void product()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ..........&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .........&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP