【问题标题】:Python - How to make multiply a given number to a given stringPython - 如何将给定数字乘以给定字符串
【发布时间】:2020-09-18 09:58:28
【问题描述】:

我想显示一副牌并输出牌的数量。

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

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) 

【问题讨论】:

    标签: python list loops for-loop append


    【解决方案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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多