Python:为什么我不能将打印值分配给变量



问题是我无法将打印值分配给变量。当我注释最后一行(print('.join(padded_strings((并取消注释代码的最后三行时,我会收到空字符串。你知道如何处理这个问题吗?

import random
DICE_ART3 = {
1: """
┌─────────┐
│         │
│    ●    │
│         │
└─────────┘
""",
2: """
┌─────────┐
│ ●       │
│         │
│       ● │
└─────────┘
""",
}
def roll_dice(n_dice=5):
my_dices = []
for n in range(n_dice):
dice =[random.randint(1,2)]
my_dices.extend(dice)
my_dices2 = []
for n in range(n_dice):
dice_str = [DICE_ART3[my_dices[n]]]
my_dices2.extend(dice_str)
strings_by_column = [s.split('n') for s in my_dices2]
strings_by_line = zip(*strings_by_column)
max_length_by_column = [
max([len(s) for s in col_strings])
for col_strings in strings_by_column
]
for parts in strings_by_line:
# Pad strings in each column so they are the same length
padded_strings = [
parts[i].ljust(max_length_by_column[i])
for i in range(len(parts))
]
print(''.join(padded_strings))
# output = ''.join(padded_strings)
#print(output)
#return(output)
roll_dice(5)

您只存储输出中的最后一行。把所有的东西都整理成一张清单。这是函数更改后的最后部分。

result = []
for parts in strings_by_line:
# Pad strings in each column so they are the same length
padded_strings = [
parts[i].ljust(max_length_by_column[i])
for i in range(len(parts))
]
output = ''.join(padded_strings)
result.append(output)
return result

然后,您可以在呼叫者中接收列表并打印它。

for line in roll_dice(5):
print(line)

您可以收集列表中的所有内容,并返回一个连接换行符的字符串。

return 'n'.join(result)

调用函数并打印结果:

print(roll_dice(5))

最新更新