附上源代码:
dataSet=[ [1,1,'yes'],
[1,1,'yes'],
[1,0,'no'],
[0,1,'no'],
[0,1,'no']]
>>>featList=[example[1] for example in dataSet]
>>>featList
[1, 1, 0, 1, 1]
>>>featList=[example[0] for example in dataSet]
>>>featList
[1, 1, 1, 0, 0]
>>>featList=[example[2] for example in dataSet]
>>>featList
['yes', 'yes', 'no', 'no', 'no']
理解如下:
以 featList=[example[1] for example in dataSet] 为例
上面这条语句是用列表推导来创建一个新的列表featList
1.先执行for语句,看example是否在dataSet数据集里,按行遍历
2.开始读的时候,发现example=[1,1,'yes']在dataSet数据集里,然后取出example[1]也就是1这个数放入featList列表里
3.继续执行for语句,发现example=[1,1,'yes']在dataSet数据集里,然后取出example[1]也就是1这个数放入featList列表里
4.继续执行for语句,发现example=[1,0,'no']在dataSet数据集里,然后取出example[1]也就是0这个数放入featList列表里
5.继续执行for语句,直到dataSet中的数据集全部按行遍历完,就结束了,打印featList中的数据,即featList=[1, 1, 0, 1, 1]