为了账号安全,请及时绑定邮箱和手机立即绑定

C#中的乘积方法

C#中的乘积方法

潇湘沐 2021-03-11 10:11:42
我正在使用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)])
查看完整描述

3 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

假设您的意思是itertools.product(看起来像给定的示例):


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;

}

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)

    Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);

输出:


1, 7

1, 8

1, 9

2, 7

2, 8

2, 9

3, 7

3, 8

3, 9


查看完整回答
反对 回复 2021-03-24
?
互换的青春

TA贡献1797条经验 获得超6个赞

对于超过列表数量有效的产品功能,您可以在此处使用我的CrossProductFunction.CrossProduct代码:


List<List<Tuple<int>>> a = new List<List<Tuple<int>>> { /*....*/ }

IEnumerable<List<Tuple<int>>> b = CrossProductFunctions.CrossProduct(a)

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


查看完整回答
反对 回复 2021-03-24
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

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


public void product()

        {

          ..........

          .........

        }


查看完整回答
反对 回复 2021-03-24
  • 3 回答
  • 0 关注
  • 358 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信