清秋2018

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

python04篇 文件操作(二)、集合

一、文件操作(二)

1.1 利用with来打开文件

复制代码
#  with  open   ,python 会自动关闭文件
with open('a.txt', encoding='utf-8') as f:  # f 文件句柄
    # 文件中没有空行,下面按行读是没问题,如果有空行就不能往下读
    while True:
        line = f.readline().strip()
        if line:
            print(line)
        else:
            break
    # 如果是大文件的话,如下处理
    for line in f:
        line = line.strip()
        if line:
            print(line)
复制代码

1.2 两个文件进行操作

复制代码
# 两个文件操作
# 1.r模式打开a文件,w模式打开b文件
# 2.读取到a文件所有内容
# 3.把替换new_str写入b文件
# 4.把a文件删除掉,把b文件更名为a文件

import os

with open('word.txt', encoding='utf-8') as fr, open('words.txt', 'w') as fn:
    for line in fr:
        line = line.strip()
        if line:
            new_line = line.replace('a', 'A')
            fn.write(new_line+'\n')
os.remove('word.txt')
os.rename('words.txt', 'word.txt')
复制代码

 

二、集合

复制代码
# set 天生去重
l = [1, 2, 3, 2, 3, 4, 1, 5, 6]
# 定义set
set1 = {1, 2, 3, 2, 3, 4, 1}
set2 = set()  # 定义空集合set
set3 = set(l)  # 强制转为set集合

set3.add(1)  # 新增元素
set3.remove(1)  # 删除元素
set3.update(set2)  # 把一个集合加入到另一个集合中
# 交集
print(set3.intersection(set1))  # 取交集 等同于 set3 & set1
print(set3 & set1)
# 并集
print(set3.union(set1))
print(set3 | set1)
# 差集
print(set3.difference(set1)) # 在一个集合中存在,在另一个集合中不存在。此语句中就是set3中存在,set1中不存在的
print(set3 - set1)
# 对称差集
print(set3.symmetric_difference(set1))  # 去掉两个集合交集之外的部分
print(set3 ^ set1)

# 集合也可以循环
for s in set3:
    print(s)
复制代码

 

三、三元表达式、列表生成式

3.1 三元表达式

复制代码
#  三元表达式
age = 18
# 原写法
if age < 18:
    v = '未成年人'
else:
    v = '成年人'

# 三元表达式 写法  只能是if else可以用,  不能
v = '未成年人' if age < 18 else '成年人'
复制代码

3.2 列表生成式

# 列表生成式
a = [1, 2, 3, 4, 5]

c = [str(i) for i in a]
d = [str(i) for i in a if i % 2 != 0]  # 可以加上if条件

 

posted on   清秋2018  阅读(172)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示