脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python for循环生成列表的实例

Python for循环生成列表的实例

2021-03-05 00:38白水你一定要努力啊 Python

今天小编就为大家分享一篇Python for循环生成列表的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

一般Python for语句前不加语句,但我在机器学习实战中看到了这两条语句:

?
1
2
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
2
3
4
list_0 = [x*x for x in range(5)]
print(list_0)
#输出:
#[0, 1, 4, 9, 16]

以上这篇Python for循环生成列表的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/baishuiniyaonulia/article/details/79301092

延伸 · 阅读

精彩推荐