遍历字典并按顺序打印其值

发布于 2024-09-18 19:38:35 字数 650 浏览 11 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雨的味道风的声音 2024-09-25 19:38:35

您可以通过组合几个列表推导式在一行中完成此操作:

print ' '.join(letter for letter, count in hand.iteritems() for i in range(count))

让我们一点一点地分解它。我将使用一个有几个大于 1 的计数的示例字典来显示重复部分的工作情况。

>>> hand
{'h': 3, 'b': 1, 'e': 2}
  1. 以我们可以迭代的形式获取字母和计数。

    <前><代码>>>>列表(hand.iteritems())
    [('h', 3), ('b', 1), ('e', 2)]

  2. 现在只剩下字母了。

    <前><代码>>>> [字母对字母,手数数.iteritems()]
    [‘h’、‘b’、‘e’]

  3. 将每个字母重复 count 次。

    <前><代码>>>> [字母对字母,手数。iteritems() for i in range(count)]
    ['h'、'h'、'h'、'b'、'e'、'e']

  4. 使用str.join将它们连接成一个字符串。

    <前><代码>>>> ' '.join(字母对字母,手数。iteritems() for i in range(count))
    '嗯嗯'

You can do this in one line by combining a couple of list comprehensions:

print ' '.join(letter for letter, count in hand.iteritems() for i in range(count))

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.

>>> hand
{'h': 3, 'b': 1, 'e': 2}
  1. Get the letters and counts in a form that we can iterate over.

    >>> list(hand.iteritems())
    [('h', 3), ('b', 1), ('e', 2)]
    
  2. Now just the letters.

    >>> [letter for letter, count in hand.iteritems()]
    ['h', 'b', 'e']
    
  3. Repeat each letter count times.

    >>> [letter for letter, count in hand.iteritems() for i in range(count)]
    ['h', 'h', 'h', 'b', 'e', 'e']
    
  4. Use str.join to join them into one string.

    >>> ' '.join(letter for letter, count in hand.iteritems() for i in range(count))
    'h h h b e e'
    
残疾 2024-09-25 19:38:35

也许是你的##code?

dispHand.append(letter)

更新

要打印您的列表,请执行以下操作:

for item in dispHand:
    print item,

Your ##code perhaps?

dispHand.append(letter)

Update:

To print your list then:

for item in dispHand:
    print item,
℉服软 2024-09-25 19:38:35

没有嵌套循环的另一种选择

"".join((x+' ') * y for x, y in hand.iteritems()).strip()

another option without nested loop

"".join((x+' ') * y for x, y in hand.iteritems()).strip()
雪落纷纷 2024-09-25 19:38:35

用于

" ".join(sequence)

打印不带逗号和括号的序列。

如果序列中有整数或其他内容

" ".join(str(x) for x in sequence)

Use

" ".join(sequence)

to print a sequence without commas and the enclosing brackets.

If you have integers or other stuff in the sequence

" ".join(str(x) for x in sequence)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文