Python for迴圈生成列表
阿新 • • 發佈:2019-02-01
一般Python for語句前不加語句,但我在機器學習實戰中看到了這兩條語句:
featList = [example[i] for example in dataSet]
classList = [example[-1] for example in dataSet]
多方研究和詢問,得到如下解釋:
語句featList = [example[i] for example in dataSet]
作用為:
將dataSet中的資料按行依次放入example中,然後取得example中的example[i]元素,放入列表featList中
語句classList = [example[-1] for example in dataSet]
將dataSet中的資料按行依次放入example中,然後取得example中的example[-1]元素,放入列表classList中
總而言之,類似上述兩種for迴圈形式可以很方便地用來建立列表,如下例:
list_0 = [x*x for x in range(5)]
print(list_0)
#輸出:
#[0, 1, 4, 9, 16]