关于我在Python里用cin&cout
2026-08-12 15:33:49
发布于:湖北
因为本人竞赛打的不多,所以尽管实力有,但是分数很低。这也就直接导致我可以去炸鱼
但是嘻哈赛要求用Python,用Python的话输入就很难受(input+split太猎奇了)。弱者适应环境,强者改变环境,于是我写了一个cin | cout Python平替出来
代码:
global_input = []
def init_input():
global global_input
try:
while True:
global_input += input().split()
except EOFError:
pass
class Value:
def __init__(self, value):
self.value = value
def get(self):
return self.value
def set(self, value):
self.value = value
def __str__(self):
return str(self.value)
class ConsoleInput:
def __init__(self):
pass
def __rshift__(self, other: Value):
put = global_input.pop(0)
if isinstance(other.value, int):
other.set(int(put))
elif isinstance(other.value, float):
other.set(float(put))
elif isinstance(other.value, str):
other.set(put)
else:
other.set(put)
return self
class ConsoleOutput:
def __init__(self):
pass
def __lshift__(self, other: Value | str):
print(other, end='', flush=True)
return self
def var(value):
return Value(value)
cin = ConsoleInput()
cout = ConsoleOutput()
ConsoleInput & ConsoleOutput就是这里cin & cout的类,使用了运算符重载使其可以使用>>和<<。
因为input是读到换行符结束,和竞赛里的空格分隔变量天生不匹配,于是使用了一个global_input列表来存储提前,用init_input将多余的空白字符处理掉。
由于Python没有引用参数传递,因此这里用一个包装类Value来模拟指针手动引用传递,因为Python中自定义类在传参中是引用传递
然后就可以快乐在Python里用cin & cout啦~
(其实本来是想发灌水区的,因为内容太猎奇了。但是灌水区更猎奇,所以发学习区了)
全部评论 1
不不不
a,b=map(int,input().split())
print(a+b)1周前 来自 江西
0别忘了sum
print(sum(int,input().split()))1周前 来自 上海
0xing
1周前 来自 江西
0























有帮助,赞一个