Is there a python function which returns all possible combinations of completions for given set of tokens:
tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]
complete(tokens,"foo","barB")
should return:
[["Afoo","barBX"],["Afoo","barBY"],["fooB","barBX"],["fooB","barBY"]]
There is no function like that as far as I know, but this is a simple thing to do using loops:
def complete(tokens, foo, bar):
return [(i, j) for i in tokens if foo in i for j in tokens if bar in j]
Definitely not super efficient though! You can use generators to do the same thing:
def complete(tokens, foo, bar):
return ((i, j) for i in tokens if foo in i for j in tokens if bar in j)
Break it down into a search step and 'find combinations' step using 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)
I get all the foo and the barB then I combine the two lists
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)
output:
[('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)
output:
[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.