我有一个单词列表(在我的例子中是域),我需要将这个列表分成几组,每组包含的字符不能超过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发布于 2021-01-30 07:34:04
在添加到结果中之前,必须检查添加新元素是否会超过最大值。
当你达到极限时,你不应该中断循环,只需在结果中添加一个空行即可。
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),因为它已经是一个字符串。
发布于 2021-01-30 07:39:40
你就快到了!如果您想以嵌套列表的形式获得结果,这里有另一个答案(使用起来可能比纯文本更实用)。
domains = ['google.com', 'yahoo.com', 'bing.com', 'microsoft.com', 'apple.com', 'amazon.com']
max_chars = 20
chunk_size = 0
chunks = [[]]
for domain in domains:
if chunk_size + len(domain) > max_chars:
chunk_size = 0
chunks.append([])
chunks[-1].append(domain)
chunk_size += len(domain)
print(chunks)结果:
[
['google.com', 'yahoo.com'],
['bing.com'],
['microsoft.com'],
['apple.com', 'amazon.com']
]发布于 2021-01-30 10:13:02
您还可以使用:
domains = ['google.com','yahoo.com','bing.com','microsoft.com','apple.com','amazon.com']
max_chars=20
out = [""]
for d in domains:
if len(d) + len(out[-1].strip()) > max_chars:
out.append(f"{d}\n")
else:
out[-1] = f"{out[-1].strip()}\n{d}\n"
print(*out, sep="\n")google.com
yahoo.com
bing.com
microsoft.com
apple.com
amazon.comhttps://stackoverflow.com/questions/65963065
复制相似问题