使用字符串输入和列表理解初始化对象列表-input().split()会导致Value Error



我正在尝试使用列表理解来读取四行输入,并将这些行转换为对象列表。

这是我的代码:

class Person:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def __str__(self):
return "[Person = {} {} {}]".format(self.x, self.y, self.z)

def main():
n = int(input())

li = [[Person(int(x), int(y), int(z)) for x, y, z in input().split()][0] for i in range(n)]

for p in li:
print(str(p))
if __name__ == "__main__":
main()

这是我的输入:

4
34 45 56
12 23 34
23 355 66666
87 67 45

但该代码并不成功。错误取决于编辑器,但我最近的错误是:li = [[Person(int(x), int(y), int(z)) for x, y, z in input().split()][0] for i in range(n)] ValueError: need more than 2 values to unpack

我相信是讨厌的input().split()引起了问题。

尽量将输入处理与业务逻辑分开。

def main():
# Phase 1: input and validation
try:
line = input()
except Exception:
sys.exit("Problem reading record count from input")
try:
n = int(line)
except ValueError:
sys.exit(f"Problem parsing record count {line}")

parameters = []
for i in range(1, n+1):
try:
line = input()
except Exception:
sys.exit(f"Problem reading record {i} from input")
try:
x, y, z = map(int, line.strip().split())
except Exception:
sys.exit(f"Problem parsing record {i}: {line}")
parameters.append((x, y, z))
# Phase 2: Business logic
li = [Person(*t) for t in parameters]  # or Person(x, y, z) for x, y, z in parameters]
for p in li:
print(str(p))

在第一阶段,您可以随心所欲地进行少量或大量的输入验证。假设您没有遇到任何导致程序退出的错误,则可以安全地创建Person对象列表。

通过使用input().split(),您创建了一个包含3个元素的列表,字符串中的每个单词对应一个元素。如果你想实现想要的开箱,你需要用另一个外部循环的函数将循环与开箱分离,比如这个:

class Person:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def __str__(self):
return "[Person = {} {} {}]".format(self.x, self.y, self.z)
def unpackSplit():
x,y,z = input().split()
return Person(int(x), int(y), int(z)) 
def main():
n = int(input())
li = [unpackSplit() for i in range(n)]
for p in li:
print(str(p))
if __name__ == "__main__":
main()

最新更新