【问题标题】:Python: using lower() at a cloned list results in endless loop? [duplicate]Python:在克隆列表中使用 lower() 会导致无限循环? [复制]
【发布时间】:2021-07-07 17:45:55
【问题描述】:

我只想通过使用 lower() 以小写形式添加列表的每个条目。 我正在使用这段代码来完成任务:

MyList = ["EntryOne", "EntryTwo"]
TempList = MyList     #cloning MyList to TempList

for v in TempList:
    MyList.append(v.lower())     #Why is it also being appended into TempList ?
    print(MyList)
    print(TempList)




#expected output:
#["EntryOne", "EntryTwo", "entryone", "entrytwo"]
#["EntryOne", "EntryTwo"]

如您所见,TempList 的声明在 for 循环之外,我只是在开头声明它。没有将小写字母附加到 TempList 的代码。

因此这个脚本永远循环。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你的错误是你在第 2 行的陈述:

TempList = MyList     #cloning MyList to TempList

这是不正确的。它不会克隆您的列表。

改用.copy()

TempList = MyList.copy()

【讨论】:

  • 谢谢,这对我有帮助!
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 2011-08-23
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多