我正在尝试一个练习,其中用户输入一个正整数,输出应该是一个七段显示转换。
每个数字都使用散列符号进行转换,因此无论输入什么数字,每个单独的数字都会转换为散列符号并添加到空字符串中。
这是我的代码:
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))
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,它会垂直输出转换后的数字,而不是水平输出。
我试图在同一行上输出每个转换后的数字。
我尝试剥离换行符,但仍然没有水平打印出每个数字。
关于如何做到这一点的任何想法?我是 Python 新手,所以任何帮助将不胜感激!
Gre*_*Guy 10
首先,使用字典来保存您的表示。这比拥有一大堆变量和相应的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))
Run Code Online (Sandbox Code Playgroud)
概念证明:
>>> seven_segment(98765432.01)
### ### ### ### ### # # ### ### ### #
# # # # # # # # # # # # # #
### ### # ### ### ### ### ### # # #
# # # # # # # # # # # # #
### ### # ### ### # ### ### # ### #
Run Code Online (Sandbox Code Playgroud)