Python 在“停止循环”时停止循环;“项目用完”;即使没有';I don’我们不能达成适当的if条款

Python 在“停止循环”时停止循环;“项目用完”;即使没有';I don’我们不能达成适当的if条款,python,string,list,for-loop,concatenation,Python,String,List,For Loop,Concatenation,我想编写一些代码,获取项目列表并将它们(用逗号分隔)连接到长字符串中,其中每个字符串的长度不超过预定义的长度。 例如,对于此列表: colors = ['blue','pink','yellow'] 如果最大长度为10个字符,则代码的输出将为: 长字符串0:蓝色、粉色 长线1:黄色 我创建了下面的代码(见下文),但它的缺陷是连接项的总长度小于允许的最大长度,或者它创建了一个或多个长字符串,而列表中剩余项的连接总长度小于最大长度 我想问的是:在下面的代码中,当项目用完并且连接太短以至于没有到达“

我想编写一些代码,获取项目列表并将它们(用逗号分隔)连接到长字符串中,其中每个字符串的长度不超过预定义的长度。 例如,对于此列表:

colors = ['blue','pink','yellow']
如果最大长度为10个字符,则代码的输出将为:

长字符串0:蓝色、粉色

长线1:黄色

我创建了下面的代码(见下文),但它的缺陷是连接项的总长度小于允许的最大长度,或者它创建了一个或多个长字符串,而列表中剩余项的连接总长度小于最大长度

我想问的是:在下面的代码中,当项目用完并且连接太短以至于没有到达“else”子句时,如何“停止”循环

非常感谢:)

导入pyperclip
#理论错误:当单个项目超过最大长度时。对于本规范的预期用途,将永远不会发生。
raw_list=pyperclip.paste()
拆分列表=原始列表。拆分()
unique_items_list=list(set(split_list))#请注意,set是无序集合,并且不维护原始顺序。对于这段代码的目的来说,现在的方式并不重要,但要记住它。查看更多:http://stackoverflow.com/a/7961390/2594546
打印“列表中有%d个项目”。%len(拆分列表)
打印“列表中有%d个唯一项”。%len(唯一项列表)
max_length=10 35; salesforce的过滤器最多允许1000个字符,但不想在代码的其余部分硬编码,以防万一。
长字符串列表=[]
short_list=[]将保存最大长度字符long str的项目。
总长度=0
已处理的项目=[]将用于健全性检查
对于唯一项目列表中的i:

如果当前为total_len+len(i)+1,则在
else
情况下,您不会对
i
执行任何操作,因此会遗漏项目,如果循环中的最后一个项目未填充
短列表,则不要处理该列表

最简单的解决方案是使用
i
在以下位置重新启动
short_list

short_list = [i]
total_len = 0
并在
for
循环后检查
短列表中是否有剩余内容,如果有,则进行处理:

if short_list:
    list_of_long_strs.append(",".join(short_list))
如果
检查:

new_len = total_len + len(i)
if new_len < max_length:
    ...
elif new_len == max_length:
    ...
else:
    ...
“,”。join(…)
表示永远不会发生)

并使用以下命令整理代码的最后一部分(我将切换到):


更广泛地说,我会这样做:

def process(unique_items_list, max_length=10):
    """Process the list into comma-separated strings with maximum length."""
    output = []
    working = []
    for item in unique_items_list:
        new_len = sum(map(len, working)) + len(working) + len(item)
                # ^ items                  ^ commas       ^ new item?
        if new_len <= max_length:
            working.append(item)
        else:
            output.append(working)
            working = [item]
    output.append(working)
    return [",".join(sublist) for sublist in output if sublist]

def print_out(str_list):
    """Print out a list of strings with their indices."""
    for index, item in enumerate(str_list):
        print("Long string {0}:".format(index))
        print(item)

好的,我的OP中描述的问题的解决方案实际上非常简单,包括2个修改:

第一条——其他条款:

    else:
    long_str = ",".join(short_list)
    list_of_long_strs.append(long_str)
    items_processed.extend(short_list)                                      #for sanity checking
    del short_list[:]                                                       # in order to empty the list.
    short_list.append(i)                                                    # so we won't lose this particular item
    total_len = len(i)
这里的主要问题是在删除short_列表后追加i,这样循环转到else子句的项就不会丢失。类似地,total_len被设置为该项的len,而不是像以前一样设置为0

正如上面友好的评论所建议的,else下的if-else是多余的,所以我把它去掉了

第二部分:

residual_items_concatenated = ",".join(short_list)
list_of_long_strs.append(residual_items_concatenated)
这一部分确保当短字符串列表由于总长度<最大长度而不能“生成”else子句时,它的项仍然被连接并作为另一项添加到长字符串列表中,就像它以前的朋友一样


我觉得这两个小小的修改是解决我问题的最好办法,因为它保留了大部分代码,只更改了几行,而不是从sratch重新编写。

我假设不允许您使用
''.join()
使用
break
操作符退出循环当循环处理完所有
唯一项列表时,循环将已经结束
;这就是
for
循环的要点!您是否为这个“bug”编写了测试?您是否有一个示例输入列表,其中出现了您描述的情况?@Optimesh但请注意,您的理智检查只检查您是否在某个点向
short_list
添加了正确数量的内容,不管你是否已经将它们连接到
list\u of_long\u strs
。谢谢你的回答,但这对我不起作用。。。尝试将max_length设置为10并运行:ab cd ef gh ij kl mn op==>kl,gh不会被连接。另外,您将如何在循环中解决它?@Optimesh我添加了一个更具python风格的示例implementation@Optimesh哦,请注意,您的版本在
else
案例中没有对
i
做任何处理,因此您最终会遗漏一些项目。谢谢。我将很快进行调查,并根据需要投票/选择正确的选项。:)
def process(unique_items_list, max_length=10):
    """Process the list into comma-separated strings with maximum length."""
    output = []
    working = []
    for item in unique_items_list:
        new_len = sum(map(len, working)) + len(working) + len(item)
                # ^ items                  ^ commas       ^ new item?
        if new_len <= max_length:
            working.append(item)
        else:
            output.append(working)
            working = [item]
    output.append(working)
    return [",".join(sublist) for sublist in output if sublist]

def print_out(str_list):
    """Print out a list of strings with their indices."""
    for index, item in enumerate(str_list):
        print("Long string {0}:".format(index))
        print(item)
>>> print_out(process(["ab", "cd", "ef", "gh", "ij", "kl", "mn"]))
Long string 0:
ab,cd,ef
Long string 1:
gh,ij,kl
Long string 2:
mn
    else:
    long_str = ",".join(short_list)
    list_of_long_strs.append(long_str)
    items_processed.extend(short_list)                                      #for sanity checking
    del short_list[:]                                                       # in order to empty the list.
    short_list.append(i)                                                    # so we won't lose this particular item
    total_len = len(i)
residual_items_concatenated = ",".join(short_list)
list_of_long_strs.append(residual_items_concatenated)