3 回答
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
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,但是在功能和设计上相似。
添加回答
举报