【问题标题】:Python, printing separate index's from dictionaryPython,从字典中打印单独的索引
【发布时间】:2017-10-18 02:16:39
【问题描述】:

这是我的代码的缩短版本。基本上,我有一本字典,其中存储了一个包含我的 ascii 字母的列表。我提示用户选择字母,然后使用特殊设计打印出来。第二个用户输入用于决定如何打印字母。 'h' = 水平,'v' = 垂直。垂直部分完美运行。水平的没有。

def print_banner(input_string, direction):
'''
Function declares a list of ascii characters, and arranges the characters in order to be printed.
'''
ascii_letter = {'a': [" _______ ",
                      "(  ___  )",
                      "| (   ) |",
                      "| (___) |",
                      "|  ___  |",
                      "| (   ) |",
                      "| )   ( |",
                      "|/     \|"]}
    # Branch that encompasses the horizontal banner
if direction == "h":
    # Letters are 8 lines tall
    for i in range(8):
        for letter in range(len(input_string)):
            # Dict[LetterIndex[ListIndex]][Line]
            print(ascii_letter[input_string[letter]][i], end=" ")
            print(" ")

# Branch that encompasses the vertical banner
elif direction == "v":
    for letter in input_string:
        for item in ascii_letter[letter]:
            print(item)


def main():
    user_input = input("Enter a word to convert it to ascii: ").lower()
    user_direction = input("Enter a direction to display: ").lower()
    print_banner(user_input, user_direction)

# This is my desired output if input is aa
_______   _______ 
(  ___  ) (  ___  )
| (   ) | | (   ) |
| (___) | | (___) |
|  ___  | |  ___  |
| (   ) | | (   ) |
| )   ( | | )   ( |
|/     \| |/     \|

#What i get instead is:
 _______ 
 _______ 
(  ___  )
(  ___  )
| (   ) |
| (   ) |
| (___) |
| (___) |
|  ___  |
|  ___  |
| (   ) |
| (   ) |
| )   ( |
| )   ( |
|/     \|
|/     \|

【问题讨论】:

  • 你几乎做对了,只有第二个打印必须不缩进。

标签: python-3.x dictionary printing


【解决方案1】:

您可以zip 将这些线条放在一起,然后加入它们:

if direction == "h":
    zipped = zip(*(ascii_letter[char] for char in input_string))
    for line in zipped:
        print(' '.join(line))

或者只用索引:

if direction == "h":
    for i in range(8):
        for char in input_string:
            print(ascii_letter[char][i], end=' ')
        print()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2017-04-26
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多