python_基本语法学习_2

本文深入探讨了Python编程中的各种实用技巧,包括枚举、迭代器的创建与使用,链式操作的应用,以及时间处理、文件操作等核心功能。通过具体示例,展示了如何进行字符串操作、文件读写及时间格式转换,适合各水平的Python开发者学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


# 枚举
s = ['a', 'b', 'c']
for i, v in enumerate(s):
    print(i, v)

# 创建迭代器
class TestIter():
    def __init__(self,lst):
        self.lst = lst
    def __iter__(self):
        print('__iter__ is called')
        return iter(self.lst)

# t = TestIter()
t = TestIter([1,3,5,7,9])

for e in t:
    print(e)
# 同理
for e in t.__iter__():
    print(e)


r = [1,2,3]
for i in range(len(r)-1,-1,-1):
    print(r[i])


# 打包
# 聚合各个可迭代对象的迭代器:
x = [3,2,1]
y = ['a','b','c']
list(zip(x,y))

for i ,j in zip(y,x):
    print(i,j)


# 过滤器
# 函数通过 lambda 表达式设定过滤条件,保留 lambda 表达式为True的元素:
fil = filter(lambda x: x>10, [1,21,3,4,8,22])
for e in fil:
    print(e)

# 链式操作
from operator import (add, sub)
def add_or_sub(a,b,oper):
    return (add if oper=='+' else sub)(a,b)

# split 分割
s = 'I love python'.split(' ')

# replace 替代
s = 'I love python'.replace(' ', ',')

# 反转字符串
st = 'python'
''.join(reversed(st))

import time
seconds = time.time()   # 当前时间

# 浮点数转时间结构体
local_time = time.localtime(seconds)

# 时间结构体转时间字符串
str_time = time.asctime(local_time)
# 时间结构体转指定格式时间字符串
format_time = time.strftime('%Y.%m%d %H:%M:%S', local_time)

# 时间字符串转时间结构体
time.strptime(format_time,'%Y.%m.%d %H:%M:%S')


# with 读写文件
import os,sys
path = r'G:\Test'
os.listdir(path)

# 读文件
with open(path, mode='r',encoding='utf-8') as f:
    o = f.read()
    print(o)

# 写文件
w_path = r'G:\Test\1.txt'
with open(w_path, mode='w', encoding='utf-8') as f:
    w = f.write("I love python \n It\'s so simple")
    os.listdir()

# 提取后缀名
import os
os.path.splitext(w_path)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值