我的代码需要帮助,我不知道为什么我会在第10行(def plus(self,v):)中得到'IndentationError:意外的unindent',有人可以帮帮我?
from itertools import combinations
df = df.groupby("b_id").apply(lambda x: list(combinations(x["a_id"], 2))).apply(pd.Series).stack()
df = df.apply(pd.Series).reset_index().groupby([0,1])["b_id"].apply(lambda x:x.values).reset_index()
df.columns = ["a_one", "a_two", "b_list"]
df["number_of_b"] = df.b_list.apply(len)
答案 0 :(得分:1)
试试这个:
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except:
pass #TODO domething here
def plus(self, v):
new_coordinates = [x + y for x, y in zip(self.coordinates, v.coordinates)]
return Vector(new_coordinates)
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
v = Vector([8.218, -9.341])
w = Vector([-1,129, 2.111])
print (v.plus(w))
答案 1 :(得分:0)
在__init__
函数中,您错过了except
块。如果您不包含此内容,则try
语句基本上无用。请务必添加except
块来处理您的ValueError
!
答案 2 :(得分:0)
错误来自于您致电try
时需要做的就是添加except
就像这样:
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except:
# do something here to handle error
try和except概念意味着您正在尝试在python中执行操作,但如果
try
范围内发生错误,那么except
范围内的任何内容都将运行。
希望这会有所帮助:)
答案 3 :(得分:0)
我会猜测并说代码应该是这样的:
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError as e:
pass
# Code here?#
def plus(self, v):
new_coordinates = [x + y for x, y in zip(self.coordinates, v.coordinates)]
return Vector(new_coordinates)
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
if __name__ == '__main__':
v = Vector([8.218, -9.341])
w = Vector([-1,129, 2.111])
print (v.plus(w))
你提供的代码中的缩进确实是错误的,但我认为解释器期待一个'except'语句(这里只是显示通过,但你应该让它做一些事情)
答案 4 :(得分:0)
请参阅documentation on exceptions。
class Vector(object):
def __init__(self, coordinates):
# try: # every try must be paired with an 'except'
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
def plus(self, v):
new_coordinates = [x + y for x, y in zip(self.coordinates, v.coordinates)]
return Vector(new_coordinates)
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
v = Vector([8.218, -9.341])
w = Vector([-1,129, 2.111])
print (v.plus(w))