【发布时间】:2020-06-16 10:17:47
【问题描述】:
我有一个包含字符串作为元素的列表。它们都是小写的。我想修改列表,以便该列表还包含第一个字母的大写字符串。 我写了这个 for 循环:
> words = ["when", "do", "some", "any"]
with_title_words = words
>
> for u in words:
> u.title()
> with_title_words.append(u)
> print(with_title_words)
当我执行时它会无限。它输出所有以大写字母开头的字符串元素。
【问题讨论】:
-
你有一个无限循环,因为你不断地将元素添加到你正在消费的循环中。
with_title_words = words不做深拷贝。这就像一个参考。
标签: python-3.x for-loop infinite-loop