gpt4 book ai didi

c# - 在c#中调整python的itertools.product内部的for

转载 作者:行者123 更新时间:2023-11-30 23:30:28 24 4
gpt4 key购买 nike

有 python 代码将填充给定 k 的列表数量

k=4
myList = {}
for objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:
if objectOfInterest[:-1] in myList:
myList[objectOfInterest[:-1]].append(objectOfInterest[1:])
else:
myList[objectOfInterest[:-1]] = [objectOfInterest[1:]]

结果:

k=3
{'11': ['10', '11'], '10': ['00', '01'], '00': ['00', '01'], '01': ['10', '11']}

k=4
{'010': ['100', '101'], '011': ['110', '111'], '001': ['010', '011'], '000': ['000', '001'], '111': ['110', '111'], '110': ['100', '101'], '100': ['000', '001'], '101': ['010', '011']}


when k=5
{'0110': ['1100', '1101'], '0111': ['1110', '1111'], '0000': ['0000', '0001'], '0001': ['0010', '0011'], '0011': ['0110', '0111'], '0010': ['0100', '0101'], '0101': ['1010', '1011'], '0100': ['1000', '1001'], '1111': ['1110', '1111'], '1110': ['1100', '1101'], '1100': ['1000', '1001'], '1101': ['1010', '1011'], '1010': ['0100', '0101'], '1011': ['0110', '0111'], '1001': ['0010', '0011'], '1000': ['0000', '0001']}

我想将其转换为 C# 代码最好的方法是什么,我认为 LINQ 可以提供帮助......

int k =4;
string myList ="";

如何循环

objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:

看起来像c#中的吗?是 foraech item in objectOfInterest...了解事实stackoverflow answer suggests :

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

n.b.这里的struct意味着T必须是值类型或者结构体。如果您需要放入列表等对象,请将其更改为类,但要注意潜在的引用问题。

然后作为司机:

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

最佳答案

我最近在 Microsoft 面试问题的提示下编写了一个有效模拟 itertools.product 的类。可以抢here 。目前它不支持重复,但您可以模拟它。

将事情整合在一起:

//emulate the repeat step. http://stackoverflow.com/q/17865166/1180926
List<List<char>> zeroOneRepeated = Enumerable.Range(0, k)
.Select(i => '01'.ToList())
.ToList();

//get the product and turn into strings
objectsOfInterest = CrossProductFunctions.CrossProduct(zeroOneRepeated)
.Select(item => new string(item.ToArray()));

//create the dictionary. http://stackoverflow.com/a/938104/1180926
myDict = objectsOfInterest.GroupBy(str => str.Substring(0, str.Length - 1))
.ToDictionary(
grp => grp.Key,
grp => grp.Select(str => str.Substring(1)).ToList()
);

关于c# - 在c#中调整python的itertools.product内部的for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20572952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com