Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用while循环向列表中添加100个单词?_Python_Loops_While Loop - Fatal编程技术网

Python 如何使用while循环向列表中添加100个单词?

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”,“

我想在列表中添加一个单词,例如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”,“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]