Python 如何使用while循环向列表中添加100个单词?
我想在列表中添加一个单词,例如100次,这是我的代码 我的预期结果是['word','word','word'…]Python 如何使用while循环向列表中添加100个单词?,python,loops,while-loop,Python,Loops,While Loop,我想在列表中添加一个单词,例如100次,这是我的代码 我的预期结果是['word','word','word'…] i = 1 text = [ ] while i <= 100: text += 'word' i += 1 print(text) i=1 text=[] 而我“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“d”,“w”,“w”,“w”,“
i = 1
text = [ ]
while i <= 100:
text += 'word'
i += 1
print(text)
i=1
text=[]
而我“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“w”,“o”,“r”,“d”,“d”,“w”,“w”,“w”,“r”,“d”,“d”,“w”,“w”,“r”,“r”,“d”,“d”,“w”,“d”,“d”,“d”,“d”,“d”,“d”,“d”,“d”,“d”,“d”,“
所有字母都是单独添加的
斯姆比能解释为什么吗?在列表中添加100个单词的正确代码是什么
谢谢您使用extend
text = ['existing', 'words']
text.extend(['word']*100)
print(text)
您想使用text.append(word)
或text+=['word']
。将项目添加到列表时,+=
实际上与.extend
相同
由于字符串可以迭代,因此它会将每个字符单独添加到列表中尝试text+=[“word”]
或text.append(“word”)
,或只是text=[“word”]*100
您对+=
对字符串和列表的作用有误解-它会将右侧的每个项目添加到列表中。字符串是可编辑的,操作将每个字符视为一项。
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]