python - 如何摆脱使用 stdout python3 打印列表的尾随空格
问题描述
我在 python 中使用 stdout 打印输出,但它保留了它保持打印的内容最后有空格,并且rsplit()
总是给我一个错误。代码如下。
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# function to convert sorted array to a
# balanced BST
# input : sorted array of integers
# output: root node of balanced BST
def sort_array_to_bst(arr):
if not arr:
return None
# find middle
mid = (len(arr)) / 2
mid = int(mid)
# make the middle element the root
root = Node(arr[mid])
# left subtree of root has all
# values <arr[mid]
root.left = sort_array_to_bst(arr[:mid])
# right subtree of root has all
# values >arr[mid]
root.right = sort_array_to_bst(arr[mid + 1:])
return root
# A utility function to print the pre-order
# traversal of the BST
def pre_order(node):
if not node:
return
if root:
sys.stdout.write(node.data + ' ')
pre_order(node.left)
pre_order(node.right)
def no_spaces(s):
return ' '.join(s.rsplit())
if __name__ == '__main__':
arr = []
for line in sys.stdin.readline().strip().split(" "):
arr.append(line)
# arr = [7, 898, 157, 397, 57, 178, 26, 679]
# Output = 178 57 26 157 679 397 898
narr = arr[1:]
print(narr)
narr = sorted(narr, key=int)
root = sort_array_to_bst(narr)
pre_order(root)
我用输入7 898 157 397 57 178 26 679
得到输出
178 57 26 157 679 397 898.
这.
是为了说明空格,但请注意在实际输出中它只是一个空格。我试过
sys.stdout.write(node.data + ' ').rsplit()
但得到:`AttributeError:'int'对象没有属性'rsplit'。我该怎么做,或者有其他选择吗?
解决方案
这是仅在元素之间打印空格的一种方法:
if root:
if node != root:
sys.stdout.write(' ')
sys.stdout.write(str(node.data))
pre_order(node.left)
pre_order(node.right)
推荐阅读
- c# - 使用带有预加载函数的内存数据库对 EF Core 进行单元测试
- azure-aks - 无法提取图像 - 未经授权:需要身份验证 (ImagePullBackOff )
- javascript - 如何异步添加到我的数组并等待完成?
- regex - 协助正则表达式匹配
- php - 将 id 从 foreach 循环传递到另一个页面而不使用 $_GET(url 中的 id)
- python - 从 Python 调用静态 C 库
- perl - How can I use rperl with perlbrew?
- javascript - 使用参数检索对象属性
- scala - 以语法一致的方式将 args 传递给 n 个参数的 fns
- html - 我应该如何使用 styled-component 解决这些样式问题