Python从list类型、range()序列简单认识类(class)【可迭代】
作者:学习笔记666 时间:2022-09-09 14:07:20
本文实例讲述了Python从list类型、range()序列简单认识类(class)。分享给大家供大家参考,具体如下:
list类型
定义:
items = []
这就定义了一个名叫items
的list。
往里填充数据:
items.append(1)
items.append(3)
items.append(4)
print(items) # [1, 3, 4]
range序列
上面那个list,如果我们要append
进去0~9的数字。最好是利用循环。
items = []
for x in range(0,10):
items.append(x)
print(items) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
这里我们就学到了range
这个类型,range(0,10)
包含0不包含10,可以简写为range(10)
。
上面还可以这样写:
items = [x for x in range(10)]
print(items) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range()
还有第三个参数:步长
#从0到10,步长为2
items = [x for x in range(0,10,2)]
print(items) # [0, 2, 4, 6, 8]
每个元素都x3:
items = [x*3 for x in range(0,10,2)]
print(items) # [0, 6, 12, 18, 24]
每个元素都二次方 :
items = [x**2 for x in range(0,10,2)]
print(items) # [0, 4, 16, 36, 64]
什么叫 iterable可迭代
简单说就是可以进行for
循环的。
字符串、list类型、字典类型、元组类型,包括自定义的类都是可以迭代。
Python里的类
#自定义类
class Person:
#类似构造函数
def __init__(self,name):
self.name = name
def show(self):
print(self.name)
#实例化类
p = Person("jack")
p.show() # jack
注意:self
可以换成任意如abc。
如何写静态方法?
#自定义类
class Person:
@staticmethod
def version():
print("version 1.0")
@staticmethod
是注解。(是不是和Java很像?)
#实例化类
Person.version() #version 1.0
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/github_26672553/article/details/78506085
标签:Python,list,range,类
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pytorch 实现打印模型的参数值
2022-11-11 22:22:28
![](https://img.aspxhome.com/file/2023/5/99555_0s.jpg)
numpy.float32的典型用法
2022-04-30 04:36:30
Python模块结构与布局操作方法实例分析
2021-11-26 10:49:31
python右对齐的实例方法
2022-01-15 20:59:52
Anaconda+Pycharm环境下的PyTorch配置方法
2023-05-20 16:38:22
![](https://img.aspxhome.com/file/2023/2/114652_0s.jpg)
细化解析:SQL Server 2000 的各种版本
2009-02-05 15:41:00
MySQL 的启动和连接方式实例分析
2024-01-21 09:06:03
![](https://img.aspxhome.com/file/2023/8/69168_0s.png)
Django分页器的用法你都了解吗
2022-06-06 21:18:39
Python读取stdin方法实例
2022-09-07 19:03:00
![](https://img.aspxhome.com/file/2023/9/86159_0s.png)
Cython处理C字符串的示例详解
2021-12-03 01:17:27
MySql数据库基本命令集会
2011-08-05 18:43:23
python中rc1什么意思
2023-10-24 13:01:38
go 下载非标准库包(部份包被墙了)到本地使用的方法
2024-05-10 13:56:50
sql语句之数据操作介绍
2024-01-22 18:09:39
Python Queue模块详解
2023-01-13 00:42:02
超详细OpenMV与STM32单片机通信 附完整源码
2023-05-27 17:03:50
![](https://img.aspxhome.com/file/2023/7/134727_0s.jpg)
Python爬取三国演义的实现方法
2022-12-11 20:07:37
python实现的多任务版udp聊天器功能案例
2021-07-31 21:49:29
![](https://img.aspxhome.com/file/2023/1/124801_0s.png)
Python实例之wxpython中Frame使用方法
2022-10-16 00:09:07
python k-近邻算法实例分享
2022-03-26 14:47:17