【问题标题】:How to fill n tables with content of string as many times as you can?如何尽可能多地用字符串内容填充 n 个表?
【发布时间】:2018-12-13 17:08:13
【问题描述】:

基本上我想要实现的是有一个字符串,比如说“汤姆有一只猫”。并检查它会以这种方式填充例如 10x3 表的次数,而不会将单词切成两半:

"T" "o" "m" " " "h" "a" "s" " " "a" " "

"c" "a" "t" "." " " "T" "o" "m" " " " "

"h" "a" "s" " " "a" " " "c" "a" "t" "."

我目前正在尝试做的是有一个字典,其中键是行数,值是一个空字符串等于列数的表。 我不知道如何做这样的事情:

for i in range(1, rows+1)     #id's of keys of already created dict
        for n in range(columns):
            for letter in string:
                d["{}".format(i)][n] = letter

当没有空间完成下一个单词时,它应该向 id 添加 +1 并开始填充下一行。然后,当句子完成时,它应该从第一个字母开始填充。最后它应该告诉用户句子填满表格的次数(示例中为 2 次)。

我希望我能理解它,我非常感谢每一个想法!

编辑: 句子和“。”之间应该有一个空格。是“猫”的一部分。最后,程序应该用“*”填充所有空闲空间,例如:

"c" "a" "t" "." " " "T" "o" "m" " ""*"

但这是最不重要的事情。

【问题讨论】:

  • '.' 是否被视为单词 'cat.' 的一部分?
  • 句子和'.'之间应该有一个空格。是“猫”的一部分。最后,程序应该用“”填充所有空闲空间,如“c”“a”“t”“。” " " "T" "o" "m" " " "" 但这是最​​不重要的事情。
  • @usr2564301 虽然这个问题确实与您链接到的问题重复,但在我看来,该问题的答案非常不符合 Pythonic。因此,我在这里提供了一个更清洁的解决方案。

标签: python python-3.x list loops dictionary


【解决方案1】:

一个解决方案(可能不是最干净的)是这样的:

def into_grid(s, width, height):
    words = cycle(s.split(" "))
    res = ""
    row = 0
    col = 0
    next_word = next(words)
    while row < height:
        if col + len(next_word) <= width:
            res += next_word + " "
            col += len(next_word) + 1
            next_word = next(words)
        else:
            row += 1
            col = 0
            res += "\n"
    return res

【讨论】:

    【解决方案2】:

    您可以将句子拆分为单词并使用itertools.cycle循环遍历每个单词,并根据当前行的空闲空间与当前单词的长度加上前导空格来填充列表列表不为空:

    from itertools import cycle
    def fill(sentence, rows, cols):
        table = [[]]
        words = cycle(sentence.split())
        while True:
            word = next(words)
            if len(table[-1]) + len(word) + bool(table[-1]) > cols:
                table[-1].extend('*' * (cols - len(table[-1])))
                if len(table) == rows:
                    return table
                table.append([])
            if table[-1]:
                table[-1].append(' ')
            table[-1].extend(word)
    

    这样:

    fill('Tom has a cat.', 4, 10)
    

    返回:

    [['T', 'o', 'm', ' ', 'h', 'a', 's', ' ', 'a', '*'],
     ['c', 'a', 't', '.', ' ', 'T', 'o', 'm', '*', '*'],
     ['h', 'a', 's', ' ', 'a', ' ', 'c', 'a', 't', '.'],
     ['T', 'o', 'm', ' ', 'h', 'a', 's', ' ', 'a', '*']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 2016-08-15
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多