笨方法学Python 习题 32: 循环和列表

xiaoxiao2021-02-28  103

#!usr/bin/python # -*-coding:utf-8-*- the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] for number in the_count: print ("This is count %d" % number) for fruit in fruits: print ("A fruit of type:%s" % fruit) for i in change: print ("I got %r"% i) elements = [] for i in range(0,6): print ("Adding %d to the list." %i) elements.append(i) for i in elements: print ("Element was: %d" %i)

运行结果如下:

$ python ex32.py This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarters' Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5 $

加分习题

注意一下 range 的用法。查一下 range 函数并理解它。

在第 22 行,你可以可以直接将 elements 赋值为 range(0,6),而无需使用 for 循环?

在 Python 文档中找到关于列表的内容,仔细阅读以下,除了 append 以外列表还支持哪些操作?

常见问题回答

如何创建二维列表?

就是在列表中包含列表,例如这样: [[1,2,3],[4,5,6]]

列表和数组不是一样的吗?

取决于语言和实现方式。从经典意义上理解的话,列表和数组是很不同的,因为它们的实现方式不同。在 Ruby 语言中列表和数组都被叫做数组,而在 Python 中又都叫做列表。现在我们就把它叫列表吧,因为 Python 里就是这么叫的。

为什么 for-loop 可以使用未定义的变量?

循环开始时这个变量就被定义了,当然每次循环它都会被重新定义一次。

为什么 for i in range(1, 3): 只循环 2 次而非 3 次?

range() 函数会从第一个数到最后一个,但不包含最后一个数字。所以它在 2 的时候就停止了,而不会数到 3。这种含首不含尾的方式是循环中及其常见的一种用法。

elements.append() 是什么功能?

它的功能是在列表的尾部追加元素。打开 Python 命令行,创建几个列表试验一下。以后每次碰到自己不明白的东西,你都可以在 Python 的交互式命令行中实验一下。

转载请注明原文地址: https://www.6miu.com/read-24018.html

最新回复(0)