c#中的乘积方法

本文关键字:方法 | 更新日期: 2023-09-27 18:14:07

我正在使用python,我正在实现我的代码到c#和在python中有方法"产品",有人知道是否有类似的东西在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)])

c#中的乘积方法

假设您指的是itertools。产品(看起来像给出的例子):

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;
}

的被害者。这里的struct意味着T必须是一个值类型或结构。如果需要抛出对象,如List s,则将其更改为class,但要注意潜在的引用问题。

Then as a driver:

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

对于在多个列表上有效的乘积函数,您可以在这里使用我的CrossProductFunction.CrossProduct代码:

List<List<Tuple<int>>> a = new List<List<Tuple<int>>> { /*....*/ }
IEnumerable<List<Tuple<int>>> b = CrossProductFunctions.CrossProduct(a)

目前,它不像itertools.product那样接受repeat参数,但在功能和设计上是相似的。

下面是用c#编写函数的语法:

public void product()
        {
          ..........
          .........
        }

链接:

http://www.dotnetspider.com/forum/139241-How-write-function-c-.net.aspx

可以在此链接中获取有关c#中各种函数的信息