Python编程基础-小知识点

Python编程基础-小知识点

1、列表(list)
(1)列表中的每个元素都是可变的
(2)列表中的元素是有序的,每个元素对应一个位置
(3)列表可以容纳python中的任何对象

在这里插入图片描述

list_sample = [0.3, 'hello', True]
print(list_sample)

# 列表切片
res1 = list_sample[0:2]  
print(res1)

# 追加元素
list_sample.append('Hello python')
print(list_sample)

# 插入元素
list_sample.insert(0, 'pre-hello')
print(list_sample)

# 删除元素
list_sample.remove('Hello python')
print(list_sample)

# 删除元素,删除前两个元素
del list_sample[:2]
print(list_sample)

# 元素修改
list_sample[1] = 100
print(list_sample)

a = []
for i in range(10):
    a.append(i)
print(a)

# 列表推导式
b = [i for i in range(1,11)]
print(b)

c = [i**2 for i in range(1,11)]
print(c)

# 1到10中偶数的平方值
d = [i**2 for i in range(1,11) if i%2==0]
print(d)
2、字符串
# 字符串
string = 'My name'
# 字符串的索引
res = string[0]
print(res)
# 字符串的切片
res1 = string[0:2]
print(res1)
# 重复两次
res2 = string*2
print(res2)
# 字符串拼接
res3 = string + ' is python'
print(res3)

# 字符串分割
res4 = string.split()   # 默认空格分隔符
res4 = string.split(sep=',')    # 逗号分隔符
print(res4)

# 字符串字母变小写
res5 = string.lower()
print(res5)
3、字典
(1)键-值成对出现
(2)键不能重复
(3)键不可更改,值可以修改
(4)键来索引值
dic = {'h':'hello', 0.5:[0.3, 0.2], 'w':'word'}
print(dic)

# 字典中的元素无先后顺序,通过键来访问值
res = dic['w']
print(res)

# 修改
dic['h'] = 100
print(dic)

# 新增
dic['hw'] = 'hello world'
print(dic)

# 新增多个键值对
dic.update({1:2, 3:4})
print(dic)

# 删除某一个键值对
del dic['h']
print(dic)

# 字典推导式
a = {i:i**2 for i in range(10)}
print(a)

4、文件操作
(1)打开文件

在python,使用 open 函数,可以打开一个已经存在的文件,或者创建一个新文件:
open( 文件名,访问模式)
示例如下:
f = open('test.txt', 'w')

(2)写数据

使用 write() 可以完成向文件写入数据

f = open('test.txt', 'w')
f.write('hello world,\n')
f.write('i am here!\n')
f.close()
(3)读数据

使用 read(num) 可以从文件中读取数据, num 表示要从文件中读取的数据的长度(单位是字节),如果没有传入 num那么就表示读取文件中所有的数据

f = open('test.txt', 'r')
content = f.read(5)
print(content)

content2 = f.read()
print(content2)

f.close()

读数据(readlines)
readlines 可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

f = open('test.txt', 'r')
content = f.readlines()
print(type(content))

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5、lambda表达式
# 输入参数x,返回x^2给y
y = lambda x:x**2
res = y(10)
6、面向对象
# 定义类
class Human:
    # 构造函数
    def __init__(self, ag=None, se=None):
        self.age = ag       # 类的属性
        self.sex = se       # 类的属性

    # 类的方法
    def square(self, x):
        return x**2

# 类的实例化
Jack = Human(ag=23, se='Male')

res = Jack.square(10)
res = Jack.age
res = Jack.sex
print(res)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值