Python-如何将给定数字乘以给定字符串

时间:2020-05-30 22:47:09

标签: python list loops for-loop append

我想显示一个副牌并输出卡数。

以下是卡片: 旁注:中间的是力量,最后的是该名字的牌数。

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) 

1 个答案:

答案 0 :(得分:1)

您还可以使用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')