Python for循环生成列表

为君一笑 提交于 2019-11-29 01:41:16

一般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循环形式可以很方便地用来创建列表,如下例:

1 list_0 = [x*x for x in range(5)]
2 print(list_0)
3 
4 #输出:
5 #[0, 1, 4, 9, 16]

 

————————————————
版权声明:本文为CSDN博主「白水你一定要努力啊」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/baishuiniyaonulia/article/details/79301092

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!