首页 > 解决方案 > Python问题:将间距分散到字符串,字符串总有一个特定的宽度

问题描述

在给定单词列表和空格数的情况下,需要创建一个分布特定数量空格的字符串。假设您有 3 个空格要展开并且列表有 3 个单词,结果应该是: "(word)space|space(word)space(word)"

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

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

  3. 从左到右,单词之间的空格数不应相差超过一个空格:

    例如"(word)space|space|space(word)space(word)"--> 错误(3 个空格,比 1 个)

    例如"(word)space|space(word)space|space(word)"--> 正确(2 个空格,而不是 2 个空格)

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

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

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

有一个额外的空间,无法跳转到正确的索引以插入空间。

标签: pythonfor-loopinsert

解决方案


我的解决方案将几个联合空格合并到一个字符串中,我不知道它是否是您需要的:

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 种不同情况的间距列表

#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

推荐阅读