【问题标题】:Split a list into chunks by a number of chars [Python]通过多个字符将列表拆分为块 [Python]
【发布时间】: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


    【解决方案1】:

    你必须检查添加新元素是否会超过最大值之前将它添加到结果中。

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

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

    【讨论】:

      【解决方案2】:

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

      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']
      ]
      

      【讨论】:

        【解决方案3】:

        你也可以使用:

        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.com
        

        Demo

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          • 2021-10-23
          • 2018-03-17
          • 2022-11-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多