3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
假設(shè)您的意思是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必須是值類型或結(jié)構(gòu)。class如果您需要拋出Lists之類的對象,但是要注意潛在的引用問題,請將其更改為。
然后作為驅(qū)動程序:
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貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
對于超過列表數(shù)量有效的產(chǎn)品功能,您可以在此處使用我的CrossProductFunction.CrossProduct代碼:
List<List<Tuple<int>>> a = new List<List<Tuple<int>>> { /*....*/ }
IEnumerable<List<Tuple<int>>> b = CrossProductFunctions.CrossProduct(a)
當(dāng)前,它不接受repeat參數(shù)itertools.product,但是在功能和設(shè)計(jì)上相似。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是用c#編寫函數(shù)的語法:
public void product()
{
..........
.........
}
添加回答
舉報(bào)