在Python中将整数转换为七段显示

我正在尝试一个练习,用户输入一个正整数,输出应该是七段显示转换。

每个数字都使用散列符号进行转换,因此无论输入什么数字,每个单独的数字都将转换为散列符号并添加到空字符串中。

这是我的代码:

zero = '###\n# #\n# #\n# #\n###\n\n'
one = '#\n#\n#\n#\n#\n\n'
two = '###\n  #\n###\n#  \n###\n\n'
three = '###\n  #\n###\n  #\n###\n\n'
four = '# #\n# #\n###\n  #\n  #\n\n'
five = '###\n#  \n###\n  #\n###\n\n'
six = '###\n#  \n###\n# #\n###\n\n'
seven = '###\n  #\n  #\n  #\n  #\n\n'
eight = '###\n# #\n###\n# #\n###\n\n'
nine = '###\n# #\n###\n  #\n###\n\n'

    def seven_segment_display(digit):
      if digit >= 0:
        digit = str(digit)
        digit_list = list(digit)
        new_digit = ''
        for i in range(len(digit_list)):
            if digit_list[i] == '0':
                new_digit += zero
            if digit_list[i] == '1':
                new_digit += one
            if digit_list[i] == '2':
                new_digit += two
            if digit_list[i] == '3':
                new_digit += three
            if digit_list[i] == '4':
                new_digit += four
            if digit_list[i] == '5':
                new_digit += five
            if digit_list[i] == '6':
                new_digit += six
            if digit_list[i] == '7':
                new_digit += seven
            if digit_list[i] == '8':
                new_digit += eight
            if digit_list[i] == '9':
                new_digit += nine
    return new_digit
print(seven_segment_display(123))

运行代码时,它输出的是垂直转换的数字,而不是水平输出的数字。

我正在尝试在同一行上输出每个转换后的数字。

我尝试剥离换行符,但是仍然没有水平打印出每个数字。

关于如何执行此操作的任何想法?我是Python的新手,所以我们将不胜感激!

yxc130170 回答:在Python中将整数转换为七段显示

首先,使用字典保存您的表示。这比拥有一堆变量和相应的if语句要简洁得多。

第二,您将需要分别存储7段显示器的每个水平线,因为您只能从左到右从上到下打印。您可以为此为每个数字分配一个5元组。

根据您输入的数字,列出这些表示形式。一旦拥有所有这些对象,然后将它们连接在一起并逐行打印。

representations = {
    '0': ('###','# #','###'),'1': ('  #','  #','  #'),'2': ('###','###','#  ','3': ('###','4': ('# #','5': ('###','6': ('###','7': ('###','8': ('###','9': ('###','.': ('   ','   ',}

def seven_segment(number):
    # treat the number as a string,since that makes it easier to deal with
    # on a digit-by-digit basis
    digits = [representations[digit] for digit in str(number)]
    # now digits is a list of 5-tuples,each representing a digit in the given number
    # We'll print the first lines of each digit,the second lines of each digit,etc.
    for i in range(5):
        print("  ".join(segment[i] for segment in digits))

概念证明:

>>> seven_segment(98765432.01)
###  ###  ###  ###  ###  # #  ###  ###       ###    #
# #  # #    #  #    #    # #    #    #       # #    #
###  ###    #  ###  ###  ###  ###  ###       # #    #
  #  # #    #  # #    #    #    #  #         # #    #
###  ###    #  ###  ###    #  ###  ###    #  ###    #
本文链接:https://www.f2er.com/3155575.html

大家都在问