有一些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
我最近写了一个类,它有效地模拟了
itertools.product
,这是由一个微软面试问题引起的。你可以抓住它here。它目前不支持repeat
,但您可以模仿它。在整合:
相关问题 更多 >
编程相关推荐