本文主要是介绍流畅的Python(1)- 一摞Python风格的纸牌,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 1. namedtuple 具名元祖
- 1.2 代码
- 2. 特殊方法覆写
1. namedtuple 具名元祖
namedtuple的特点是只有少量属性,没有方法。
1.2 代码
# 导入相关数据库
import random
from collections import namedtuple
from random import choice# 定义单个纸牌Cards类,有属性rank 和 suit
Cards = namedtuple('Cards', ['rank', 'suit'])# 一套纸牌
class FrechDeck:# 批量生成列表ranks和suitsranks = [str(n) for n in range(2, 11)] + list('JQKA')suits = "spades diamonds clubs hearts".split()def __init__(self):# 初始化生成一套纸牌self._cards = [Cards(rank, suit) for rank in self.ranksfor suit in self.suits]# 返回长度def __len__(self):return len(self._cards)# 根据序号返回值def __getitem__(self, item):return self._cards[item]# 实例化纸牌
my_frenchdeck = FrechDeck()
# 获取纸牌的长度
print(f"len(my_frenchdeck)={len(my_frenchdeck)}")# 循环迭代获得纸牌
for i in my_frenchdeck:print(i)
print("*" * 100)
# 对纸牌进行切片处理
print(f"my_frenchdeck[-1]={my_frenchdeck[-1]}")
print(f"my_frenchdeck[5]={my_frenchdeck[5]}")
print(f"my_frenchdeck[0:5]={my_frenchdeck[0:5]}")
print(f"my_frenchdeck[:-5]={my_frenchdeck[:-5]}")
print(f"choice(my_frenchdeck)={choice(my_frenchdeck)}")# 给每个纸牌花色进行赋权重
suit_values = dict(spades=3, diamonds=1, clubs=0, hearts=2)# 根据传入的单个card计算出总的权重,依据suit_value+rank
def spades_high(card):rank_value = FrechDeck.ranks.index(card.rank)return rank_value * len(suit_values) + suit_values[card.suit]print("*" * 100)
i = -1
# 根据总权重值进行排序
for card in sorted(my_frenchdeck, key=spades_high):i += 1print(f"i={i},card={card},weights = {spades_high(card)}")
2. 特殊方法覆写
from math import hypot# 定义一个向量Vector
class Vector:def __init__(self, x=0, y=0):self.x = xself.y = y# 覆写向量打印的写法def __repr__(self):return "Vector(%r,%r)" % (self.x, self.y)# 覆写向量abs方法,向量的模def __abs__(self):return hypot(self.x, self.y)# 覆写向量加法def __add__(self, other):x = self.x + other.xy = self.y + other.yreturn Vector(x, y)def __bool__(self):# return bool(abs(self))return bool(self.x or self.y)# 覆写向量和标量的乘法def __mul__(self, scale):return Vector(self.x * scale, self.y * scale)vector1 = Vector(2, 3)
vector2 = Vector(4, 5)
print(f"bool(vector1)={bool(vector1)}")
print(f"vector1 + vector2={vector1 + vector2}")
print(f"abs(vector1)={abs(vector1)}")
print(f"vector1 * 3={vector1 * 3}")
bool(vector1)=True
vector1 + vector2=Vector(6,8)
abs(vector1)=3.6055512754639896
vector1 * 3=Vector(6,9)
- 用生成器初始化元组和数组
symbols = '$¢£¥€¤'
# 用将原来的列表[]改成元组就是生成器()
mytuple = tuple(ord(s) for s in symbols)
print(mytuple)
# output:
# (36, 162, 163, 165, 8364, 164)
这篇关于流畅的Python(1)- 一摞Python风格的纸牌的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!