【问题标题】:How to add 100 words to a list using while loop?如何使用 while 循环将 100 个单词添加到列表中?
【发布时间】:2021-03-03 14:52:54
【问题描述】:

我想为 ex 添加一个词。 100 次到一个列表,这是我的代码

我的预期结果是 ['word', 'word', 'word'...]

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', ...

所有字母都是单独添加的,

smbdy 能解释一下原因吗?将 100 个单词添加到列表中的正确代码是什么?

谢谢

【问题讨论】:

  • 试试text += ["word"]text.append("word"),或者只是text = ["word"] * 100
  • 你对+=对字符串和列表的作用有误解
  • += operation for a list is equivalent to .extend - 它将右侧的每个项目添加到列表中。字符串是可迭代的,操作将每个字符视为一个项目。

标签: python loops while-loop


【解决方案1】:

您想改用text.append(word)text += ['word']。将项目添加到列表时,+= 实际上与 .extend 相同。

由于字符串可以被迭代,它会将每个字符单独添加到列表中

【讨论】:

    【解决方案2】:

    使用扩展。

    text = ['existing', 'words']
    text.extend(['word']*100)
    
    print(text)
    

    【讨论】:

      【解决方案3】:
      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]
      

      【讨论】:

        猜你喜欢
        • 2018-10-23
        • 1970-01-01
        • 2018-07-06
        • 1970-01-01
        • 2023-03-25
        • 2012-04-15
        • 2012-05-09
        • 2012-12-28
        • 2023-03-28
        相关资源
        最近更新 更多