预览后续内容
在本练习中,您将对比使用「非 Pythonic」与「Pythonic」两种方式来遍历列表。
names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
假设您想收集上述列表中长度不少于 6 个字母的名字。在其他编程语言中,常见做法是创建一个索引变量(i),用 i 来迭代列表,并通过 if 语句收集长度不少于 6 的名字:
i = 0
new_list= []
while i < len(names):
if len(names[i]) >= 6:
new_list.append(names[i])
i += 1
下面我们来看看更「Pythonic」的做法。
本练习是课程的一部分
高效编写 Python 代码
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Print the list created using the Non-Pythonic approach
i = 0
new_list= []
while i < len(names):
if len(names[i]) >= 6:
new_list.append(names[i])
i += 1
print(____)