I need to create a list comprehension and add one extra item at the start and end. Is there a better way than just using a helper function to do it?
# convert tuple from permutation into a list with predecessor and successor
def perm_to_list(predecessor, perm, successor):
result = [predecessor]
result.extend(list(perm))
result.append(successor)
return result
candidates = [perm_to_list(prefix, x, suffix)
for x in permutations(something)]
To match the sample code (where you add prefix and suffix to each element of a list comprehension)
candidates = [[prefix] + list(x) + [suffix] for x in permutations(something)]
To answer the question you actually asked (to add a prefix and suffix to the list comprehension itself)
candidates = [prefix] + [somefunction(x) for x in permutations(something)] + [suffix]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With