- Python数据整理
- (美)提尔塔吉奥蒂·萨卡 (印)舒布哈迪普·罗伊乔杜里
- 347字
- 2025-02-14 17:47:18
练习2:生成列表
我们将检验生成列表的各种方法。
1.使用append方法创建一个列表:

输出结果如下:

这里我们首先声明一个空列表,然后使用for循环对其进行赋值。append方法只用于Python列表数据类型。
2.使用以下命令生成列表:

部分输出如图1-4所示。
这是一个我们需要掌握的非常强大的工具——列表推导式。列表推导式的能力来自这样一个事实,即我们可以在推导式内部使用条件。
3.使用while循环遍历列表,以理解while循环和for循环之间的区别:

部分输出如图1-5所示。

图1-4 列表推导式

图1-5 使用while循环输出list_1的内容
4.创建可以被5整除的数字列表list_3:

输出的将是一个以5为增量递增到100的数字列表:

5.两个列表相加生成新的列表:

输出如下:

6.使用extend关键字扩展字符串:

部分输出如图1-6所示。

图1-6 list_1的内容
第二个操作会改变原始列表(list_1)并将list_2的所有元素附加到list_1。所以,使用时要小心。