我想在列表中添加一个单词,例如100次,这是我的代码
我预期的结果("字"、"词","词"…]
i = 1
text = [ ]
while i <= 100:
text += 'word'
i += 1
print(text)
输出为->‘w’,‘o’,‘r’,‘d’,‘w’,‘o’,‘r’,‘d’,‘w’,‘o’,‘r’,‘d’,‘w’,‘o’,‘r’,‘d’,‘w’,…
所有字母单独添加,
我能解释为什么吗?向列表中添加100个单词的正确代码是什么?
谢谢
您希望使用text.append(word)
或text += ['word']
代替。当向列表中添加项目时,+=
与.extend
实际上是相同的。
由于字符串可以迭代,所以它将每个字符单独添加到列表中
使用extend.
text = ['existing', 'words']
text.extend(['word']*100)
print(text)
mul=100
text = ['existing', 'words']
# repeat the text n-times
m_text=[[x]*mul for x in text]
# flattened list
flat_list = [item for sublist in m_text for item in sublist]