Python 如何向列表中的特定元素添加字符串?

Python 如何向列表中的特定元素添加字符串?,python,list,Python,List,我有一个可变长度的单词列表,希望为每个比最长单词短的单词添加空格。我稍后将其划分为子列表,因此希望此列表中的每个子列表的长度相同 我的单词列表可以如下所示: words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle'] len_list = [] for word in words: len_list.append(len(word)) max_word_size = max(len_list

我有一个可变长度的单词列表,希望为每个比最长单词短的单词添加空格。我稍后将其划分为子列表,因此希望此列表中的每个子列表的长度相同

我的单词列表可以如下所示:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']
len_list = []
for word in words:
    len_list.append(len(word))
max_word_size = max(len_list)

for item in words:
    len_item = len(item)
    if len_item < max_word_size:
        add_space = int(max_word_size - len_item)
        words.append(" " * add_space)
    else:
        break
到目前为止,我的代码如下所示:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']
len_list = []
for word in words:
    len_list.append(len(word))
max_word_size = max(len_list)

for item in words:
    len_item = len(item)
    if len_item < max_word_size:
        add_space = int(max_word_size - len_item)
        words.append(" " * add_space)
    else:
        break

这会给我在列表末尾添加空格,这不是我想要的。有人知道如何解决这个问题吗?

您可以使用填充较短的单词来执行以下操作:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']

ml = max(map(len, words))  # maximum length
words = [w.ljust(ml) for w in words]  # left justify to the max length


# OR, in order to make it a mutation on the original list
# words[:] = (w.ljust(ml) for w in words)

请注意,字符串本身是不可变的,因此您不能向其添加空格,您必须使用新的填充字符串重新生成列表。

您可以执行以下操作,使用填充较短的单词:

words = ['sax', 'stol', 'kul', 'kök', 'äpple', 'rum', 'katt', 'toalettrulle']

ml = max(map(len, words))  # maximum length
words = [w.ljust(ml) for w in words]  # left justify to the max length


# OR, in order to make it a mutation on the original list
# words[:] = (w.ljust(ml) for w in words)
请注意,字符串本身是不可变的,因此不能向其追加空格,必须使用新的填充字符串重新生成列表

这不是一个完美的答案,因为我使用了一个新的列表,下面是我的代码:

这不是一个完美的答案,因为我使用了一个新的列表,下面是我的代码:


我可以问一下为什么每件物品都要有相同的长度吗?这可能有点不合适,但如果是为了输出,您可以这样做,因为您只是在单词列表中添加一个新的空格字符串。而您应该将空格添加到项目并在列表中更新它。您确定您的意思不是项目+=*添加空格,而不是单词。追加*添加空格?然后用这个更新列表,正如@Yehven所说。追加用于在列表末尾的案例空间中添加项目,这就是列表的工作方式。我可以问一下为什么希望每个项目都具有相同的长度吗?这可能有点不合适,但如果是为了输出,您可以这样做,因为您只是在单词列表中添加一个新的空格字符串。而您应该将空格添加到项目并在列表中更新它。您确定您的意思不是项目+=*添加空格,而不是单词。追加*添加空格?然后用它更新列表,正如@Yehven所说。appending用于在列表末尾的case空格中添加项,这就是列表的工作方式。