python学习


一、python参数解析

Python可以使用argparse模块来解析输入参数,以下是一个示例:

import argparse
# 创建解析器
parser = argparse.ArgumentParser(description='This is a program to add two numbers.')
# 添加输入参数
parser.add_argument('-a', '--num1', type=int, help='the first number')
parser.add_argument('-b', '--num2', type=int, help='the second number')
# 解析输入参数
args = parser.parse_args()
# 输出结果
print(args.num1 + args.num2)

使用argparse模块创建了一个解析器并添加了两个输入参数,分别是数字a和数字b。然后,我们使用parse_args()方法来解析输入参数,并将结果存储在args变量中。最后,我们输出两个数字的和。当我们在命令行运行该脚本并输入-a 5 -b 6时,将输出11,即5和6的和。


二、python类的使用

以下是一个简单的Python类示例,演示了如何定义并使用类:

class Person:
    # 定义一个类变量
    num_of_persons = 0
    
    # 初始化方法
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.num_of_persons += 1
        print("A new person has been created.")
    
    # 实例方法
    def introduce(self):
        print(f"My name is {self.name}, and I am {self.age} years old.")
    
    # 类方法
    @classmethod
    def print_num_of_persons(cls):
        print(f"There are {cls.num_of_persons} persons.")
    
    # 静态方法
    @staticmethod
    def say_hello():
        print("Hello!")

在上面的示例中,我们定义了一个名为Person的类,它具有以下特性:

  • 类变量num_of_persons:表示已创建的Person对象的数量。
  • 初始化方法__init__:当我们创建一个新的Person对象时,它将记录对象的姓名和年龄,并将num_of_persons加1。
  • 实例方法introduce:允许一个Person对象介绍自己。
  • 类方法print_num_of_persons:输出目前已创建的Person对象数量。
  • 静态方法say_hello:输出一条静态的问候语。

以下是如何使用这个Person类的一些例子:

# 创建两个Person对象
person1 = Person("Alice", 18)
person2 = Person("Bob", 20)
# 调用实例方法
person1.introduce()
# 调用类方法
Person.print_num_of_persons()
# 调用静态方法
Person.say_hello()

输出:

A new person has been created.
A new person has been created.
My name is Alice, and I am 18 years old.
There are 2 persons.
Hello!

三、python数据结构

Python有以下常用的数据结构:

  1. 列表(List)

  2. 元组(Tuple)

  3. 字典(Dictionary)

  4. 集合(Set)

1. 列表

列表是一种可变的有序数据集合,在Python中可以使用中括号[]来表示。

# 创建一个空列表

my_list = []

# 向列表中添加元素

my_list.append(1)

my_list.append('hello')

my_list.append(True)

# 访问列表中的元素

print(my_list[0]) # 输出: 1

print(my_list[1]) # 输出: 'hello'

print(my_list[2]) # 输出: True

# 使用for循环遍历列表

for item in my_list:

    print(item)

2. 元组

元组是一种不可变的有序数据集合,在Python中可以使用小括号()来表示。

# 创建一个元组

my_tuple = (1, 'hello', True)

# 访问元组中的元素

print(my_tuple[0]) # 输出: 1

print(my_tuple[1]) # 输出: 'hello'

print(my_tuple[2]) # 输出: True

3. 字典

字典是一种可变的无序键值对集合,在Python中可以使用大括号{}来表示。

# 创建一个字典

my_dict = {'name': 'John', 'age': 30, 'gender': 'male'}

# 访问字典中的值

print(my_dict['name']) # 输出: 'John'

print(my_dict['age']) # 输出: 30

# 修改字典中的值

my_dict['age'] = 35

# 使用for循环遍历字典

for key, value in my_dict.items():

    print(key, value)

4. 集合

集合是一种可变的无序唯一数据集合,在Python中可以使用大括号{}set()函数来表示。

# 创建一个集合

my_set = {1, 2, 3, 4, 5}

# 添加元素到集合中

my_set.add(6)

# 从集合中移除元素

my_set.remove(3)

# 计算集合的长度

print(len(my_set)) # 输出: 5

# 使用for循环遍历集合

for item in my_set:

    print(item)

以上是常见数据结构的一些使用示例,我们可以使用它们来存储和处理不同类型的数据。

python数组示例

import array
# 创建一个存储整数的数组
my_array = array.array('i', [1, 2, 3, 4, 5])
# 输出数组元素
for element in my_array:
    print(element)


# 定义一个整数数组(列表)
nums = [1, 2, 3, 4, 5]
# 访问数组元素
print(nums[0])  # 输出1
# 修改数组元素
nums[0] = 0
print(nums)  # 输出 [0, 2, 3, 4, 5]
# 数组迭代
for num in nums:
    print(num)
# 计算数组长度
print(len(nums))  # 输出 5
# 添加元素到数组
nums.append(6)
print(nums)  # 输出 [0, 2, 3, 4, 5, 6]
# 从数组删除元素
nums.remove(2)
print(nums)  # 输出 [0, 3, 4, 5, 6]
# 数组排序
nums.sort()
print(nums)  # 输出 [0, 3, 4, 5, 6]
# 从数组中获取最大和最小值
print(max(nums))  # 输出 6
print(min(nums))  # 输出 0

四、python文件读取

读取目录下所有文件,并写到另一个目录下(只写1/6)

import os
import sys
from datetime import datetime

def process_files(src_dir, dst_dir):
    for filename in os.listdir(src_dir):
        src_path = os.path.join(src_dir, filename)
        dst_path = os.path.join(dst_dir, filename)
        # Skip directories
        if os.path.isdir(src_path):
            os.makedirs(dst_path, exist_ok=True)
            process_files(src_path, dst_path)
        else:
            with open(src_path, 'r', errors='ignore') as src_file:
                with open(dst_path, 'w') as dst_file:
                    content = src_file.read()
                    length = len(content)
                    step = max(1, length // 6)
                    print(src_file.name, length, step)
                    #for i in range(0, length, step):
                    dst_file.write(content[0:step])


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: python3 read.py <src_path> <dst_path>")
    else:
        st=datetime.now()
        print("start time is ", st)
        src_path = sys.argv[1]
        dst_path = sys.argv[2]
        process_files(src_path, dst_path)
        end_file=os.path.join(src_path, "end_flag")
        with open(end_file, 'w') as f:
            pass
        print("start time is ", st)
        print("end time is ", datetime.now())

总结

提示:这里对文章进行总结:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自动驾驶小哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值