一. 索引
1. 元素的索引编号代表元素与列表开头的距离(索引从0开始)
2. 索引
-1
是指列表的最后一个元素,-2
是倒数第二个3. 列表切片:
>>> q3 = months[6:9]
冒号左侧的索引编号 6 是切片开始的位置。切片持续到第二个索引编号 9(请注意,切片不包括索引编号为 9 的元素,但包括编号为 6 的元素,以此类推)
4. 切片简化方式:
a. 获得一个从原始列表开头开始的子列表
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> first_half = months[:6] >>> print(first_half) ['January', 'February', 'March', 'April', 'May', 'June']
b. 获得一个在原始列表的末尾结束的子列表
>>> second_half = months[6:] >>> print(second_half) ['July', 'August', 'September', 'October', 'November', 'December']
5. 与
string
、float
和int
一样,list
也是一种类型。在我们看到的所有类型中,列表与字符串最为相似:这两种类型都支持索引、切片、len
函数和in
运算符。
二. For循环
我们可以使用列表来存储数据序列,并使用 for 循环来遍历列表
def list_sum(input_list): sum=0 for s in input_list: sum+=s #sum = s # todo: Write a for loop that adds the elements # of input_list to the sum variable return sum
# create a new list of capitalized names without modifying the original list capitalized_names = [] #create a new, empty list for name in names: capitalized_names.append(name.title()) #add elements to the new list
三. While循环
For 循环是 "定迭代" 的一种,它表示循环主体将执行指定次数。while循环指循环重复未知次数,直到满足某些条件时循环才会结束
#TODO: Implement the nearest_square function def nearest_square(limit): a=0 while a**2<limit: a+=1 return (a-1)**2 test1 = nearest_square(40)