微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按多个字符将列表拆分为多个块 [Python]

如何解决按多个字符将列表拆分为多个块 [Python]

我有一个单词列表(在我的例子中是域),我需要将这个列表分成几组,每个组应该包含不超过 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

解决方法

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

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

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) 因为它已经是一个字符串。

,

你快到了! 这是另一个答案,如果您想将结果作为嵌套列表(可能比纯文本更实用)。

domains = ['google.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']
]
,

您也可以使用:

array[i](i);

domains = ['google.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")

Demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。