简体   繁体   English

浏览字典并按顺序打印其值

[英]going through a dictionary and printing its values in sequence

def display_hand(hand):
    for letter in hand.keys():
        for j in range(hand[letter]):
            print letter, 

Will return something like: behquwx . 将返回类似以下内容: behquwx 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. 不过,请允许我扩大o库格尔的回答:库格尔的方法回答了我的问题。 However i kept running into an additional issue: the function would always return None as well as the output. 但是我一直遇到另一个问题:函数将始终返回None以及输出。 Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. 原因:每当您不从Python中的函数显式返回值时,都将隐式返回None。 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. 在Kugel的方法中,我走得更近,但手仍埋在FOR循环中。

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. 我将使用一个示例字典,该字典的两个计数大于1,以显示重复部分的工作情况。

>>> 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. 重复每个字母count次数。

     >>> [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. 使用str.join将它们连接为一个字符串。

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

Your ##code perhaps? 您的##代码?

dispHand.append(letter)

Update : 更新

To print your list then: 然后打印列表:

for item in dispHand:
    print item,

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

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM