gpt4 book ai didi

Python 在一行上打印两个东西

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:59 25 4
gpt4 key购买 nike

我正在学习 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"。在这种情况下,我们将只使用一个空字符串。参见 herehere .

输出:

current hand: a a a b b b b c 

关于Python 在一行上打印两个东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com