遍历字典并按顺序打印其值
def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print letter,
将返回类似:behquw x
。这是所需的输出。
如何修改此代码以仅在函数完成循环时获取输出?
像下面的代码这样的东西会给我带来问题,因为在打印输出时我无法摆脱逗号和单引号等字典元素:
def display_hand(hand):
dispHand = []
for letter in hand.keys():
for j in range(hand[letter]):
##code##
print dispHand
更新 我发现约翰的回答非常优雅。不过,请允许我扩展 Kugel 的回应: 库格尔的方法回答了我的问题。然而,我一直遇到一个额外的问题:该函数总是返回 None 以及输出。原因:只要您没有从 Python 中的函数显式返回值,就会隐式返回 None 。我找不到明确归还手的方法。在 Kugel 的方法中,我走得更近了,但手仍然埋在 FOR 循环中。
def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print letter,
Will return something like: b e h q u w x
. This is the desired output.
How can I modify this code to get the output only when the function has finished its loops?
Something like below code causes me problems as I can't get rid of dictionary elements like commas and single quotes when printing the output:
def display_hand(hand):
dispHand = []
for letter in hand.keys():
for j in range(hand[letter]):
##code##
print dispHand
UPDATE
John's answer is very elegant i find. Allow me however to expand o Kugel's response:
Kugel's approach answered my question. However i kept running into an additional issue: the function would always return None as well as the output. Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. I couldn't find a way to explicitly return the hand. In Kugel's approach i got closer but the hand is still buried in a FOR loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过组合几个列表推导式在一行中完成此操作:
让我们一点一点地分解它。我将使用一个有几个大于 1 的计数的示例字典来显示重复部分的工作情况。
以我们可以迭代的形式获取字母和计数。
<前><代码>>>>列表(hand.iteritems())
[('h', 3), ('b', 1), ('e', 2)]
现在只剩下字母了。
<前><代码>>>> [字母对字母,手数数.iteritems()]
[‘h’、‘b’、‘e’]
将每个字母重复
count
次。<前><代码>>>> [字母对字母,手数。iteritems() for i in range(count)]
['h'、'h'、'h'、'b'、'e'、'e']
使用
str.join
将它们连接成一个字符串。<前><代码>>>> ' '.join(字母对字母,手数。iteritems() for i in range(count))
'嗯嗯'
You can do this in one line by combining a couple of list comprehensions:
Let's break that down piece by piece. I'll use a sample dictionary that has a couple of counts greater than 1, to show the repetition part working.
Get the letters and counts in a form that we can iterate over.
Now just the letters.
Repeat each letter
count
times.Use
str.join
to join them into one string.也许是你的##code?
更新:
要打印您的列表,请执行以下操作:
Your ##code perhaps?
Update:
To print your list then:
没有嵌套循环的另一种选择
another option without nested loop
用于
打印不带逗号和括号的序列。
如果序列中有整数或其他内容
Use
to print a sequence without commas and the enclosing brackets.
If you have integers or other stuff in the sequence