一些数据的基本操作

# 数据排序及各对象属性方法相关
def test_1():
    # copy相关,主要为可变对象需要copy例如(list,dict,set),其它则不用
    import copy
    original_list = [1, 2, [3, 4]]


    # 浅拷贝
    shallow_copied_list = original_list.copy()
    shallow_copied_list[0] = 99          # 不影响原列表
    shallow_copied_list[2][0] = 88       # 会影响原列表!


    # 深拷贝
    deep_copied_list = copy.deepcopy(original_list)
    deep_copied_list[0] = 77             # 不影响原列表
    deep_copied_list[2][0] = 66          # 也不会影响原列表!


    print("原列表:", original_list) #[1, 2, [88, 4]]
    print("浅拷贝:", shallow_copied_list)   #[99, 2, [88, 4]]
    print("深拷贝:", deep_copied_list)  #[77, 2, [66, 4]]


    list1 = [1,2,5,3,8]
    # 进行排序,原地排序
    # list1.sort()
    # print(list1)
    # 进行排序,返回新列表,reverse,false为从小到大
    print(sorted(list1,reverse=False))  #[1, 2, 3, 5, 8]
    # 按字符串长度排序
    words = ["apple", "banana", "cherry", "date"]
    sorted_words = sorted(words, key=lambda x: len(x))
    print(sorted_words) #['date', 'apple', 'banana', 'cherry']
    # 根据字典的某个key的value进行排序
    students = [
        {'name': 'Tiyong', 'grade': 90},
        {'name': 'Bob', 'grade': 85},
        {'name': 'Toy', 'grade': 95}
    ]
    students_1 = sorted(students,key=lambda x: x['grade'])
    # 奇数偶数排序,key返回的false和true默认为0,1,因此先排false再拍true
    print(students_1) #[{'name': 'Bob', 'grade': 85}, {'name': 'Tiyong', 'grade': 90}, {'name': 'Toy' 'orange': 1, 'grape': 1}), 'grade': 95}]  
    print(sorted(list1,key=lambda x: x%2==0))   #[1, 5, 3, 2, 8]


    test_str = "Hello World"
    # 分割字符串,-1代表全部分割,正数代表分割前几个
    print(test_str.split('o',maxsplit=-1))  #['Hell', ' W', 'rld']
    # 合并字符串,list,set,str
    print('-'.join(test_str)) #H-e-l-l-o- -W-o-r-l-d
    # 替换字符串
    print(test_str.replace('e','l')) #Hlllo World
    # 删除list,remove是删除匹配值,pop是删除下标
    # list1.remove(8)
    # list1.pop(0)
    print(list1) #[1, 2, 5, 3, 8]
    # 生成序列
    print(list(range(0,10,2)))  #[0, 2, 4, 6, 8]
    # 随机数
    import random
    print(random.randint(1,10),random.choice([True,False])) #7 True
    # 打乱对象
    random.shuffle(words)
    print(words)    #['cherry', 'apple', 'date', 'banana']
    # 随机取出片段
    print(random.sample(words,2))   #['apple', 'banana']
    # map调用指定函数
    li = [1, 2, 3, 4, 5]
    new_list = map(lambda x:x*2,li)
    print(list(new_list))   #[2, 4, 6, 8, 10]
    # filter筛选元素
    new_list = filter(lambda x: x % 2 != 0, li)
    print(list(new_list))   #[1, 3, 5]
    # 时间方面
    from datetime import datetime
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))     #2025-07-01 14:55:14
    print(datetime.now() - datetime(2025,5,19,17,41))   #42 days, 21:14:14.889201


    # collections的Counter,主要用于统计计算
    from collections import Counter, deque, defaultdict
    from collections import OrderedDict, namedtuple


    data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
    data_1 = ['bigapple','bigbanana']
    data_2 = ['bigapple','bigbanana']
    data_1.append(data)
    print(data_1)   #['bigapple', 'bigbanana', ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']]
    data_2.extend(data)     #['bigapple', 'bigbanana', 'apple', 'banana', 'apple', 'orange', 'banana', 'apple']
    counter = Counter(data_2)
    print(data_2)
    print("统计结果:", counter)     #统计结果: Counter({'apple': 3, 'banana': 2, 'bigapple': 1, 'bigbanana': 1, 'orange': 1})


    print("最常见的元素:", counter.most_common(2))  #最常见的元素: [('apple', 3), ('banana', 2)]


    counter.update(['banana', 'banana', 'grape'])
    print("更新后的统计:", counter) #更新后的统计: Counter({'banana': 4, 'apple': 3, 'bigapple': 1, 'bigbanana': 1, 'orange': 1, 'grape': 1})


    del counter['apple']
    print("删除后的计数器:", counter)   #删除后的计数器: Counter({'banana': 4, 'bigapple': 1, 'bigbanana': 1, 'orange': 1, 'grape': 1})


    counter1 = Counter(a=3, b=1)
    counter2 = Counter(a=1, b=2, c=3)
    print("交集:", counter1 & counter2)     #交集: Counter({'a': 1, 'b': 1})
    print("并集:", counter1 | counter2)     #并集: Counter({'a': 3, 'c': 3, 'b': 2})
   
    # 需要处理双端操作的时候可以使用deque,多线程环境使用,本身就是安全的不需要额外加锁
    d = deque([1, 2, 3])
    d.append(4)          # deque([1, 2, 3, 4])
    d.appendleft(0)      # deque([0, 1, 2, 3, 4])
    d.extend([5, 6])     # deque([0, 1, 2, 3, 4, 5, 6])
    d.extendleft([-1, -2]) # deque([-2, -1, 0, 1, 2, 3, 4, 5, 6])(顺序反转)
    d = deque([0, 1, 2, 3, 4])
    d.pop()              # 返回 4,deque 变为 [0, 1, 2, 3]
    d.popleft()          # 返回 0,deque 变为 [1, 2, 3]
    d.remove(2)          # 删除 2,deque 变为 [1, 3]
    d.clear()            # deque 变为 deque([])
    d = deque([1, 2, 3, 4, 5])
    d.rotate(2)   # 向右旋转 2 步 → deque([4, 5, 1, 2, 3])
    d.rotate(-1)  # 向左旋转 1 步 → deque([5, 1, 2, 3, 4])

 

posted @ 2025-07-01 16:40  树下黑猫  阅读(5)  评论(0)    收藏  举报