python - 列表列表中的组合
问题描述
拥有以下列表列表['boundari', 'special', ['forest', 'arb'], 'abod']
,我想获得以下组合:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
abod
删除最后一项(我需要保留)时应用下一个产品的最近解决方案:
print([list(p) for p in product([toks[:2]], *toks[2:])])
[[['boundari', 'special'], 'forest'], [['boundari', 'special'], 'arb']]
但是,我没有得到正确的组合:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
解决方案
你可以这样做:
arr = ['boundari', 'special', ['forest', 'arb'], 'abod']
def get_combinations(arr):
n = len(arr)
def _get_combinations(so_far, idx):
if idx >= n:
yield so_far[:]
return
if isinstance(arr[idx], list):
for val in arr[idx]:
so_far.append(val)
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
else:
so_far.append(arr[idx])
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
yield from _get_combinations([], 0)
expected_ans = [
['boundari', 'special', 'forest', 'abod'],
['boundari', 'special', 'arb', 'abod'],
]
assert list(get_combinations(arr)) == expected_ans
推荐阅读
- java - 将数据从第二个活动传递到第三个活动
- c++ - 在 tensorflow C++ 中在同一 GPU 上使用多个并行进程时推理时间较慢
- c# - ASP.NET 使用 XML 元素将 HTML 放入资源文件
- javascript - Safari 11“防止跨站点跟踪”打破 Facebook 登录
- jdbc - Kafka Connect JDBC:它是否可以在批量模式下加载banle,但前提是表中的任何记录发生更改?
- typescript - 为什么我的属性注入尝试除了未定义之外没有注入任何东西?
- rest - 如何在 SugarCRM 中使用刷新令牌?
- python - 张量流预测
- python - 如何通过 pandas 列从嵌套的三元组 for 循环中输出完整的结果表?
- sql - 在 MS SQL 约束中创建唯一检查 + 附加检查