數據結構和循環

一. 索引

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. 與 stringfloat 和 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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章