题目要求:23456789TJQKA(数字,由小到大排)
DCHS(花色,由小到大排)
数字优先,数字相同比花色,牌由花色和数字组成
例子
input(In the csv file):
(输入是二维的,可能输入多行)
CA , SA , S2 , C2 , ST , H3
SJ , DK , SQ
Output:
[ ’ SA ’ , ’ CA ’ , ’ DK ’ , ’ SQ ’ , ’ SJ ’ , ’ ST ’ , ’ H3 ’ , ’ S2 ’ , ’ C2 ’]
我写的(只写了一半)
#csv
with open("C:\Users\lenovo\Desktop\file.txt",'r',encoding='utf_8') as file2:
(我打开了一个文件)
lst=file2.read().splitlines()
file2.close()
file=str(lst).replace("'","")
print(file)
#排序
#赋值
{'T':10,'J':11,'Q':12,'K':13,'A':14}
{'D':100,'C':101,'H':102,'S':103}
for x in range(len(file)):
for y in range(len(file)-x-1):
if file[y][1] < file[y+1][1]:
file[y],file[y+1] = file[y+1],file[y]
print(file)
问题
我不知道如何在数字相同时比较花色并且上面if循环给我报indexerror
file这个变量是字符串类型,不是列表类型,所以对其的操作可能产生错误。修改如下:
参考链接:
python int 型数组_Python入门教程(一):初识Numpy_weixin_39918961的博客-CSDN博客
python如何读取文件的每一行_FFlyHero的博客-CSDN博客_python读取文件的每一行
https://jingyan.baidu.com/article/574c5219240bf32d8d9dc19d.html
http://www.kaotop.com/it/21171.html
代码如下:
import numpy as np
def readPoker(s): #根据输入的扑克字符串来返回扑克牌数字和花色对应的数字数组
pokerChars={'T':10,'J':11,'Q':12,'K':13,'A':14}
decorChars={'D':100,'C':101,'H':102,'S':103}
s1 = s[1]
if s1=='T' or s1=='J' or s1=='Q' or s1=='K' or s1=='A' :
s1 = pokerChars[s1]
else :
s1 = int(s1)
s2 = decorChars[s[0]]
#https://blog.csdn.net/weixin_39918961/article/details/113538162
return np.array([s2,s1])
file=[]
#https://blog.csdn.net/yiqiedouhao11/article/details/123457043
#从文件读取所有的扑克牌字符串到列表file
with open("poker.txt",'r',encoding='utf_8') as f:
for lst in f.readlines():
#lst=file2.readline()
lst = lst.replace(' ','')
lst = lst.replace('\n','')
lst = lst.split(',')
#print("type(lst_=",type(lst),"lst=",lst)
#https://jingyan.baidu.com/article/574c5219240bf32d8d9dc19d.html
file.extend(lst)
#print("file=",file)
#排序
#赋值
pokers=[]
pokersName=[]
#遍历扑克牌字符串列表,根据其值将对应的扑克牌数字数组存入pokers列表,以便下面进行排序
for s in file:
#print("s=",s)
pokerNum = readPoker(s)
#print(pokerNum)
pokers.append(pokerNum)
pokersName.append(s)
#print(pokers)
#http://www.kaotop.com/it/21171.html
count = len(pokers)
#根据题目的扑克大小规则,排序扑克数字数组列表和扑克字符串列表
for i in range(count):
for j in range(i+1,count):
if pokers[i][1]<pokers[j][1]:
pokers[i], pokers[j] = pokers[j], pokers[i]
pokersName[i], pokersName[j] = pokersName[j], pokersName[i]
elif pokers[i][1]==pokers[j][1] and pokers[i][0]<pokers[j][0] :
pokers[i], pokers[j] = pokers[j], pokers[i]
pokersName[i], pokersName[j] = pokersName[j], pokersName[i]
#打印结果
print( pokersName)
poker.txt:
CA , SA , S2 , C2 , ST , H3
SJ , DK , SQ
运行结果: