如何根据一组列表中的每个值创建元组列表
我想根据一组列表中的每个值创建一个元组列表。列表集可以打开,但对于示例,我有以下三个字符串列表。
L1: (one, two three)
L2: (a, b, c)
L3: (yes, no)
我想返回一个元组列表,其中每个元组中都有每个列表中的元素。在本例中,我将有 18 种组合 (3 x 3 x 2),
T1: (one, a, yes)
T2: (one, a, no)
T3: (one, b, yes)
T4: (one, b, no)
T5: (one, c, yes)
T6: (one, c, no)
T7: (two, a, yes)
依此类推。在本例中我们使用 Java。
List<List<String>> list = getInput();
List<List<String> tuples = combinations(list);
其中 getInput() 返回我的输入(L1、L2、L3),组合创建我的输出(T1、T2、T3...)
I'd like to create a list of tuples from each value within a set of lists. The set of lists can be open, but for the example I have the following three lists of Strings.
L1: (one, two three)
L2: (a, b, c)
L3: (yes, no)
I would like to return a list of tuples, where in each tuple I have on element from each list. In this case, I will have 18 combinations (3 x 3 x 2)
T1: (one, a, yes)
T2: (one, a, no)
T3: (one, b, yes)
T4: (one, b, no)
T5: (one, c, yes)
T6: (one, c, no)
T7: (two, a, yes)
and so on. In this case we're using Java.
List<List<String>> list = getInput();
List<List<String> tuples = combinations(list);
where getInput() returns my input (L1, L2, L3), and combinations creates my output (T1, T2, T3...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于@Ted Hopp 发布了一个递归解决方案,我正在发布一个非递归解决方案。
这是一个可行的解决方案,
Since @Ted Hopp posted a recursive solution i am posting a non-recursive solution.
This is a working solution,
使用递归函数这应该很容易。这是未经测试的:
This should be pretty easy with a recursive function. This is untested:
如果任何列表共享公共元素,则上述递归解决方案将失败。
使用堆栈并推送/弹出元素而不是从列表中添加/删除它们可以解决此问题。
这是递归方法的修改后的代码:
The recursive solution above fails if any of the lists shares common elements.
Using a Stack and pushing/popping elements rather than adding/removing them from a list fixes it.
Here's the revised code for the recurse method: