[英]How to overwrite array elements that have already been printed out in a previous print statement?
I have a 2D array of 4x4 matrix. 我有一个4x4矩阵的2D数组。 I am printing the array in formatted form.
我正在以格式化的形式打印数组。 Now I want to add a sleep time of say 1 sec and then for two of the elements in array (I know the index), want to overwrite those two elements with the values in the same print.
现在我想添加1秒的休眠时间,然后对于数组中的两个元素(我知道索引),想要用同一个打印中的值覆盖这两个元素。
I have tried adding end = "\\r" and then updating the array elements, But this is not helping. 我试过添加end =“\\ r”然后更新数组元素,但这没有帮助。 It's still printing the new array underneath the previous print.
它仍然在上一个打印件下方打印新阵列。
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in duplicate_array]), end = "\r")
time.sleep(1)
duplicate_array[0] = 0
duplicate_array[1] = 1
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in duplicate_array]))
Expected output - 预期产量 -
a a 2 3
4 5 6 a
8 9 10 11
12 13 14 15
I want to display the above array first and then after 1 sec lapse, I want to just overwrite the elements where the value is 'a' with respective indexes. 我想首先显示上面的数组,然后在1秒后失效,我想用相应的索引覆盖值为'a'的元素。 I this case 0 and 1.
我这个案例是0和1。
After 1 sec array will become - 1秒后阵列将成为 -
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
I don't want to overwrite the whole array, just the elements at 0 and 1. So that user sees just those elements changing and not the whole array. 我不想覆盖整个数组,只需要覆盖0和1处的元素。这样用户只能看到那些元素在变化,而不是整个数组。
Actual Output with the code I have - 使用我的代码实际输出 -
a a 2 3
4 5 6 7
8 9 10 11
a a 2 34 15
4 5 6 7
8 9 10 11
12 13 14 15
if you don't want to use third party libraries, so this code is best practice for you. 如果您不想使用第三方库,那么此代码最适合您。 i got expected result on windows
我在Windows上得到了预期的结果
import os, time
array = [['a','a' ,'2', '3'], ['4', '5', '6', 'a'], ['12', '13', '14', '15']]
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in array]), end = "\r")
time.sleep(2)
array[0][0] = '0'
array[0][1] = '1'
array[1][3] = '7'
os.system('cls')
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in array]), end = "\r")
input()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.