是否有python函数返回给定标记集的所有可能的完成组合:
-------------------
|col_1|col_2|col_3|
------+-----+------
| c11 | c12 | c13 |
| c21 | c22 | c23 |
| c 31| c 32| c 33|
-------------------
应该返回:
tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]
complete(tokens,"foo","barB")
答案 0 :(得分:3)
据我所知,没有这样的功能,但使用循环这是一件简单的事情:
def complete(tokens, foo, bar):
return [(i, j) for i in tokens if foo in i for j in tokens if bar in j]
但绝对不是超级高效!您可以使用生成器执行相同的操作:
def complete(tokens, foo, bar):
return ((i, j) for i in tokens if foo in i for j in tokens if bar in j)
答案 1 :(得分:0)
将其分解为搜索步骤并找到组合'使用itertools步骤
from itertools import product
def complete(tokens, searches):
# search
matches = [[t for t in tokens if s in t] for s in searches]
# find all combinations https://docs.python.org/3/library/itertools.html
return product(*matches)
tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]
search = ["foo", "barB"]
combinations = list(complete(tokens, search)
答案 2 :(得分:0)
我得到了所有的foo和barB 然后我结合两个列表
tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]
foo = [a for a in tokens if "foo" in a]
barB = [a for a in tokens if "barB" in a]
x = [(a, b) for a in foo for b in barB]
print(x)
输出:
[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]
tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]
x = [(a, b) for a in tokens if "foo" in a for b in tokens if "barB" in b]
print(x)
输出:
[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]