gpt4 book ai didi

python - 按多个字符将列表拆分为 block [Python]

转载 作者:行者123 更新时间:2023-12-02 02:24:05 24 4
gpt4 key购买 nike

我有一个单词列表(在我的例子中是域),我需要将此列表分成几组,每组应包含不超过 N 个字符(=字节)。一件重要的事情是每组的最后一个单词不应该在中间中断。我的意思是不应该出现这样的情况:

google.com
yahoo.com
bin

在我的代码中,我只设法检索第一组,我不知道如何进行适当的循环以将列表拆分为多个 block 。

domains = ['google.com','yahoo.com','bing.com','microsoft.com','apple.com','amazon.com']


domains = list(domains)
text = ""
chars_sent=0
max_chars=20

for each_domain in domains:
if chars_sent > max_chars:
chars_sent = 0
break
text += each_domain+"\n"
chars_sent += len((str(each_domain)))
print(text)

预期输出:

google.com
yahoo.com <--- 19 chars in this part

bing.com <--- 8 chars in this part

microsoft.com <--- 13 chars in this part

apple.com
amazon.com <--- 19 chars in this part

最佳答案

在将新元素添加到结果之前,您必须检查添加新元素是否会超出最大值。

当你达到限制时,你不应该跳出循环,只需在结果中添加一个空行即可。

domains = ['google.com','yahoo.com','bing.com','microsoft.com','apple.com','amazon.com']

text = ""
chars_sent=0
max_chars=20

for each_domain in domains:
if chars_sent + len(each_domain) > max_chars:
chars_sent = 0
text += "\n"
text += each_domain+"\n"
chars_sent += len(each_domain)

print(text)

不需要使用 list(domain) 因为它已经是一个列表,也不需要使用 str(each_domain) 因为它已经是一个字符串。

关于python - 按多个字符将列表拆分为 block [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65963065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com