【发布时间】:2021-01-29 23:26:38
【问题描述】:
我有一个单词列表(在我的例子中是域),我需要将此列表分成几组,每组不应超过 N 个字符(=字节)。重要的一点是,每组中的最后一个词不应该在中间中断。我的意思是不应该有这样的情况:
google.com
yahoo.com
bin
在我的代码中,我只设法检索了第一组,我不知道如何进行适当的循环以将列表分成多个块。
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
【问题讨论】:
标签: python list sorting chunks