从lis中的项生成限制为若干字符的混合字符串

2024-06-07 04:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算在列表中获取字符串值,以找到充分利用25个字符限制的子字符串的不同组合。你知道吗

我目前正在处理这个问题:

如果我有一个值列表:

lorem = ['when', 'the fox jumped over the moon'] 

由于列表中的第二个字符串,结果是:

limited = ['when']

lorem = ['when', 'the fox jumped', 'over', 'the moon'] 

我想要一个算法可以:

  1. 搜索整个字符串列表。你知道吗
  2. 尝试生成所有组合的字符串以充分利用字符限制。你知道吗
  3. 打印3-5个不同的结果(比如1号的长度是23,2号是22,3号是18等等)

比如:

limited = ['the fox jumped the moon']

..
..

我希望这是清楚和有意义的。你知道吗

当前代码:

title_limited = []
counter = 0
while counter < 25:
    for i in lorem:
        counter += len(i)
        if counter > 25: break
        title_limited.append(i.title())

谢谢你的帮助。你知道吗


Tags: the字符串算法列表titlecounter充分利用over
1条回答
网友
1楼 · 发布于 2024-06-07 04:35:29

试试这个:

import itertools

x_raw=[el.split(' ') for el in lorem] 
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=25 # 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)   

相关问题 更多 >