简体   繁体   English

Python - 字典打印与他的值一样多的键

[英]Python - dictionary print the key as many times as his value

I want to print out all the letters in my dictionary (seen at the last line of my code) the problem is that the output is aqlmui now.我想打印出字典中的所有字母(在我的代码的最后一行中看到),问题是现在输出是aqlmui But as you guys can see the l in my dictionary is having a value of 2 so I want to print that out 2 times.但是正如你们所看到的,我字典中的 l 的值为 2,所以我想将其打印 2 次。 so the output of my program should be: aqllmui.所以我的程序的输出应该是:aqllmui。

Help would be appreciated a lot!帮助将不胜感激! :) :)

def display_hand(hand):

    row = ''
    for letter in hand:
        row += letter

       #I think i need to put an if statement here but I just don't know how to do it

    print row


display_hand({'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1})

You can also try print "".join(k*v for (k,v) in s.iteritems()) .您也可以尝试print "".join(k*v for (k,v) in s.iteritems())

Here k*v for (k,v) in s.iteritems() returns a list of key*value like ["a","i","m","ll","q","u"] and "".join(list) will join that list to make a string.这里k*v for (k,v) in s.iteritems()返回一个key*value列表,如["a","i","m","ll","q","u"]"".join(list)将加入该列表以生成一个字符串。

做就是了:

row += letter * hand[letter]

You can use string/int multiplication to perform multiple concatenations您可以使用 string/int 乘法来执行多个串联

for letter in hand:
    row += letter * hand[letter]

Or a little more clearly and efficiently:或者更清楚、更有效:

for letter, count in hand.iteritems():  # Use hand.items() in Python 3
    row += letter * count

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

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