改编python的itertools.product在c内#

2024-04-24 18:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有一些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:]]

导致:

^{pr2}$

我想把它翻译成c代码 最好的办法是什么,我在想林克能帮上忙。。。在

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

Tags: 代码in列表newforresultproductitem
1条回答
网友
1楼 · 发布于 2024-04-24 18:51:52

我最近写了一个类,它有效地模拟了itertools.product,这是由一个微软面试问题引起的。你可以抓住它here。它目前不支持repeat,但您可以模仿它。在

整合:

//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()
    );

相关问题 更多 >