Skip to main content
 首页 » 编程设计

Python 在一行上打印两个东西

2025年05月04日24Free-Thinker

我正在学习 edx python 类(class)。我在上一次作业中正确地完成了所有事情。但是,我正在努力解决这个打印问题。

我有一个函数displayHand(hand),它本质上是一个字典,键是字母,值是字母出现的次数。然后该函数打印一个字符串,其中每个键出现的次数与其值相同。例如,如果

hand={a:3, b:4, c:1} 
displayHand(hand)=a a a b b b b c 

现在在任何给定手的程序中,它希望我使用带有文本“当前手:”的 displayHand 函数显示它

同样,如果 hand={a:3, b:4, c:1} 程序应该显示

current hand: a a a b b b b c 

如何使用打印语句执行此操作?我试过 print("current hand"+str(displayHand(hand)),但这首先计算函数然后只打印 None。我不能把print("Current Hand: ") 和 displayHand(hand) 直接在下面,因为它们打印在不同的行上。我需要让它们打印在同一行上。

请您参考如下方法:

python 3:

def displayHand(dct): 
    for key, val in sorted(dct.items()):  # sorted if key order should be abc 
        print((key + " ") * val, end="") 
 
 
hand = {"a": 3, "b": 4, "c": 1} 
 
print("current hand: ", end="") 
displayHand(hand) 

注意 end="",它附加了 "" 中的任何内容。默认设置为 end="\n"。在这种情况下,我们将只使用一个空字符串。参见 here和 here .

输出:

current hand: a a a b b b b c