Python 问题:给字符串展开间距,字符串总有一个特定的宽度

Python Question: spread out spacing to string, there is a specific width for the string total

需要创建一个字符串来展开特定数量的 spaces,给定单词列表和 spaces 的数量。假设你有 3 spaces 展开并且列表有 3 个单词,结果应该是: "(word)space|space(word)space(word)"

  1. 字符串必须以单词结尾

  2. 应该也适用于不同数量的space和单词。

  3. 从左到右 space 的数量不应相差超过一个 space 中间单词:

    例如"(word)space|space|space(word)space(word)" --> 错了 (3 spaces, 比 1)

    例如"(word)space|space(word)space|space(word)" --> 正确(2 spaces,比 2 spaces)

    例如"(word)space|space(word)space(word)" --> 正确 (2 spaces, 比 1)

我试过 for 循环,但我不知道如何跳转到不同的索引,它会产生额外的 space:

word = ['123','45','6']
z = len(word)
spaces = 3

while spaces > 0:
  for i in range(1,z):
    word.insert(i,' ')
    spaces -= 1
    
print(word)

输出:['123', ' ', ' ', ' ', ' ', '45', '6']

得到一个额外的 space,无法跳转到正确的索引以插入 space。

我的解决方案是在一个字符串中合并多个联合空间,我不知道这是不是你需要的:

word = ['123', '45', '6', '789']
z = len(word)
count = 0
spaces = 5

# computes the string to be inserted (except the last one) :
sp = round(spaces / (z-1))
space = ' ' * sp    

for i in range(1, z):
    # handle the last space specifically :
    if i == z-1: space =  ' ' * (spaces - count) 
    # the target index grows with insertions :
    word.insert(i * 2 - 1, space)
    # count the number of spaces inserted :
    count += sp


print(word) #==> ['123', '  ', '45', '  ', '6', ' ', '456']

编辑:这是一个解决方案,可以在开始时将空间平均分配给最大的空间。它使用两个循环而不是一个循环:

word = ['123', '45', '6', '789', '45', '6', '13']
z = len(word)
spaces = 17

sp      = spaces / (z-1) # spaces / z as a float
spSum   = 0              # sum of integer spaces 
spacing = []             # collector

for i in range(1, z):
    new    = round(sp * i) - spSum # computes the current integer space
    spSum  += new                  # adds it to the sum
    spacing.append(new)            # and collects it

spacing = sorted(spacing, reverse = True) # Sorts the collected spaces in descending order 

for i in range(1, z):              # Finally inserts :
    word.insert(i * 2 - 1, spacing[i-1] * ' ')

这里是生成的间距列表,有 4 种不同的情况[​​=13=]

#z = 7, spaces = 17
print(spacing) #==> [3, 3, 3, 3, 3, 2] # Single smallest at end
#z = 7, spaces = 18
print(spacing) #==> [3, 3, 3, 3, 3, 3] # All equal
#z = 7, spaces = 19
print(spacing) #==> [4, 3, 3, 3, 3, 3] # Single greatest at beginning
#z = 7, spaces = 21
print(spacing) #==> [4, 4, 4, 3, 3, 3] # Other distribution