我想显示一个副牌并输出卡数。
以下是卡片:旁注:中间的是力量,最后的是那个名字的牌数。
Admiral,30,1
General,25,1
Colonel,20,2
Major,15,2
Captain,10,2
Lieutenant,7,2
Sergeant,5,4
Corporal,3,6
Private,1,10
数字代表代表该名称的卡片数量。我希望它使用append打印以下内容。我知道我想使用for循环将等级列添加到甲板上,但是我不确定如何编写代码。
输出应该是:
['Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private']
There are 30 cards in the deck.
我的代码在这里:
while True:
text = rankFile.readline()
#rstrip removes the newline character read at the end of the line
text = text.rstrip("\n")
if text=="":
break
data = text.split(",")
rankList.append(data[0])
powerList.append(int(data[1]))
numberList.append(int(data[2]))
for i in range(0, len(rankList)):
rankList.append(numberList[i]) # this wont work since number is an integer but how can I modifiy this...
rankFile.close()
print(50*"=")
print("\t\tLevel 3 Deck")
print(50*"=")
print (rankList)
print (powerList)
print (numberList)
您也可以使用list.extend
方法添加特定数量的卡:
cards = []
with open('cards.txt', 'r') as f_in:
for line in f_in:
r, p, n = line.strip().split(',')
cards.extend((r, p) for _ in range(int(n)))
ranks, powers = zip(*cards)
print(ranks)
print(powers)
打印:
('Admiral', 'General', 'Colonel', 'Colonel', 'Major', 'Major', 'Captain', 'Captain', 'Lieutenant', 'Lieutenant', 'Sergeant', 'Sergeant', 'Sergeant', 'Sergeant', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Corporal', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private', 'Private')
('30', '25', '20', '20', '15', '15', '10', '10', '7', '7', '5', '5', '5', '5', '3', '3', '3', '3', '3', '3', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1')