python 枚举 和 文件基本操作

# 二维列表推导

m = [[1,2,3],[4,5,6],[7,8,9]]
n = [[2,2,2],[3,3,3],[4,4,4]]


for i in range(len(m)):
    for j in range(len(m[i])):
        print(m[i][j] * n[i][j],end=" ")

print()

result = [m[i][j] * n[i][j] for i in range(len(m)) for j in range(len(m[i]))]
print(result)

s1 = [[m[i][j] * n[i][j] for j in range(len(m[i]))] for i in range(len(m))]
print(s1)

s2 = [[m[i][j] * n[i][j] for i in range(len(m[j]))] for j in range(len(m))]
print(s2)

a = [1,2,3]
b = [2,5,6]
c = [1,6,8]

for i in a:
    for j in b:
        for k in c:
            if i != j and j != k and i != k:
                print((i,j,k),end=" ")

print()

s = [(i,j,k) for i in a for j in b for k in c if i != j and j != k and i != k]
print(s)



# 枚举
"""
1,对于一些既定的值,不允许自己任意赋值,只能从既定的给的值中选择
2,枚举出的name不能重复
3,如果枚举中存在相同值的成员,在通过值获取枚举成员时,只能获取到第一个成员
   如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器 @unique 【要导入unique模块】
"""

from enum import Enum,unique


# @ unique  # 导入unique模块,可以限制枚举的成员值的唯一性,若是有值重复的成员,再执行就会提示错误
class color(Enum):
    red = 1
    # red = 0 # red 不能重复
    red_s = 1 # 1 的别名是red_s ,通过 1 只能获取red ,不能获取red_s
    orange = 2
    yellow = 3
    green = 4
    blue = 5
    """
    1,定义一个颜色的枚举color
    2,有6 个成员,分别是color.red,color.red_s,color.orange等6个成员
    3,每各成员的各有自己的名称和值:如,color.red 的名称是red ,值是1
    4,每个成员的类型就是它所属的枚举
    """

print(color(3))  # 通过值获取成员名称
print(color["orange"].value) # 通过成员获取值
c = color["red"] # 创建一个枚举的实例
print(c.name) # 获取实例的名称
print(c.value) # 获取实例的值

for i in color:  # 遍历枚举成员,有重复值的只能输出第一个成员
    print(i,end=" | ")

print()

for i in color.__members__.items(): # .__members__.items()可以把重复值的成员遍历输出
    print(i,end=" | ")

print()

print(color.red is color.red)  # 成员同一性比较
print(color.red is not color.blue)
print(color.red == color.blue)  # 成员值是否相等比较,直接用成员名称
print(color.red != color.blue)
print(color.red.value < color.blue.value) # 成员值大小比较,必须调用成员的属性值 .value




# 文件操作

f = open("003.txt","r+")
print(f.name)
print(f.closed)
print(f.mode)
f.write("hello girl !!")
f.write("\nI am tom,\ncan you tell me what's your name ?")
f.seek(0)
txt = f.read()
print(txt)
f.seek(0)
f.read(2)
txt = f.readline()  # 读取指针所在行指针后边的所有字符,不跨行
print(txt)
f.read(1)
txt = f.readlines() # 读取指针所在行后边文件的所有字符,按行输出到列表
print(txt)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值