【发布时间】:2019-12-25 11:20:31
【问题描述】:
我想生成以下电影的 5 种组合,将它们限制为特定的字符数量。
films = ['Pulp Fiction','The Lion King','Reservoir Dogs','The Wolf of Wall Street','Jackie Brown','The Shawshank Redemption','Django Unchained','The Godfather','Gone Girl','The Dark Knight']
我打算让字符数量可变(本例假设为 50 个字符)。
预期结果:
for i in film_combinations_limited:
i[0] = ['The Shawshank Redemption, The Wolf of Wall Street'] (49 characters inc comma)
i[1] = ['Pulp Fiction, Gone Girl, The Wolf of Wall Street'] (48 characters inc comma)
i[2] = ['Reservoir Dogs, Pulp Fiction, The Dark Knight'] (45 characters inc comma)
i[3] = ['Jackie Brown, Django Unchained, Pulp Fiction'] (44 characters inc comma)
i[4] = ['The Wolf of Wall Street, The Lion King'] (38 characters inc comma)
i[5] = ['Pulp Fiction, The Shawshank Redemption'] (38 characters inc comma)
希望充分利用字数限制,逗号和空格也需要考虑字数限制。
当前代码:
import itertools
x_raw=[el.split(' ') for el in films]
x=[el for sublist in x_raw for el in sublist] #Not sure if I understood, what do you mean by "substring" - these 2 lines will produce substring ~ word
n=50 # character limit
res=[]
for i in range(len(x)):
for obj in itertools.combinations(x, i+1):
res_temp = " ".join(obj)
#to ensure total number of characters <25 but it's high enough, that no other word from lorem/x will fit
if((len(res_temp) < n) and (n-len(res_temp)<=min([len(el) for el in [el_x for el_x in x if el_x not in obj]] or [100]))): res.append(res_temp)
这会生成一个不包含逗号或空格的组合实例。我正在尝试实现尽可能多地填充字符限制的输出。
此代码的输出无关紧要,可以从列表更改。
如需更多信息/说明,请询问。
谢谢
【问题讨论】:
-
为什么空格和逗号这么复杂?我认为您只需要遍历所有可能的组合,加入完整的电影名称(超过
', ')并检查长度是否足够短。为什么要在空间等上分裂? -
您想要最长个可能的解决方案吗?
-
@Alfe 是的,这是所希望的
标签: python list loops while-loop combinations