使用python 3和jupyter notebook(我必须为类)。
我有一个函数,通过循环多次并从另一个列表中追加一个随机选择的元素来创建一个列表。但是当我使用该函数时,它给出的列表会在新行上显示每个元素。为什么?我可以改变吗?
代码:
def create_board(length=32,seed=0,types=2):
"""
Creates a one-dimensional game board of randomly placed
letters, using as many as are specified.
"""
if types>26:
print("No, try a number smaller than 27.")
else:
board = []
letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
for i in range(length):
val=random.randint(0,(types-1))
board.append(letters[val])
return board
然后两个
print(create_board())
和
create_board()
board
输出创建的列表,但每个元素都在新行上:
[ 'B',
'B',
'A',
'B',
'A',
等等。
答案 0 :(得分:7)
这是由pretty printing引起的,默认情况下在IPython会话中处于启用状态。这可以在配置选项中关闭,也可以在会话期间通过运行pprint
magic:
In [12]: %pprint
Pretty printing has been turned OFF
In [13]: %pprint
Pretty printing has been turned ON
In [14]: %pprint
Pretty printing has been turned OFF
答案 1 :(得分:0)
对不起,也许我不明白,但如果目标是在一行上打印列表的所有元素,无论算法如何,都可能足以让你加入元素清单?
这样:
print(",".join(create_board()))
如果我们真的是偏执狂:
print(",".join([str(i) for i in create_board()]))