针对如何修复TypeError:“int”对象不可迭代?和int对象不可调用怎么解决这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展PythonFlask,TypeError:“dict”对
针对如何修复TypeError:“ int”对象不可迭代?和int对象不可调用怎么解决这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展Python Flask,TypeError:“ dict”对象不可调用、Python TypeError:“ str”对象不可用于类、python – TypeError:’KFold’对象不可迭代、Python-TypeError:“ int”对象不可调用等相关知识,希望可以帮助到你。
本文目录一览:- 如何修复TypeError:“ int”对象不可迭代?(int对象不可调用怎么解决)
- Python Flask,TypeError:“ dict”对象不可调用
- Python TypeError:“ str”对象不可用于类
- python – TypeError:’KFold’对象不可迭代
- Python-TypeError:“ int”对象不可调用
如何修复TypeError:“ int”对象不可迭代?(int对象不可调用怎么解决)
我正在尝试编写一个程序,该程序允许您输入班级中的学生人数,然后为每个学生输入3个测试成绩以计算平均值。我是编程新手,但会不断收到错误消息,我不了解它的含义或解决方法。这是我到目前为止所拥有的:
students=int(input(''Please enter the number of students in the class: ''))for number in students: first_grade=(input("Enter student''s first grade: ")) second_grade=(input("Enter student''s second grade: ")) third_grade=(input("Enter student''s third grade: "))
答案1
小编典典当你写
for number in students:
您的意图是“运行这段代码students
时间,students
我刚才输入的值在哪里”。但是在Python,你传递给事情一个for
声明需求是某种迭代对象的。在这种情况下,您想要的只是一个range
statement。这将生成一个数字列表,并且对这些数字进行迭代将使您的for
循环能够执行正确的次数:
for number in range(students): # do stuff
在幕后,range
Just会生成一个序列号列表:
>>> range(5)[0, 1, 2, 3, 4]
在您的情况下,数字到底是什么并不重要;以下两个for
语句将执行相同的操作:
for number in range(5):for number in [1, 3, 97, 4, -32768]:
但是,range
如果您需要在循环中更改某种列表(这可能是以后需要做的事情),则使用该版本被认为更惯用且更方便。
Python Flask,TypeError:“ dict”对象不可调用
遇到一个似乎很普遍的问题,但我已经完成了研究,并且看不到它在任何地方都被完全重新创建了。当我打印时json.loads(rety.text)
,我看到了所需的输出。但是,当我打电话给return时,它显示了这个错误。有任何想法吗?非常感谢您的帮助,谢谢。我正在使用FlaskMethodHandler
。
class MHandler(MethodView): def get(self): handle = '''' tweetnum = 100 consumer_token = '''' consumer_secret = '''' access_token = ''-'' access_secret = '''' auth = tweepy.OAuthHandler(consumer_token,consumer_secret) auth.set_access_token(access_token,access_secret) api = tweepy.API(auth) statuses = api.user_timeline(screen_name=handle, count= tweetnum, include_rts=False) pi_content_items_array = map(convert_status_to_pi_content_item, statuses) pi_content_items = { ''contentItems'' : pi_content_items_array } saveFile = open("static/public/text/en.txt",''a'') for s in pi_content_items_array: stat = s[''content''].encode(''utf-8'') print stat trat = ''''.join(i for i in stat if ord(i)<128) print trat saveFile.write(trat.encode(''utf-8'')+''\n''+''\n'') try: contentFile = open("static/public/text/en.txt", "r") fr = contentFile.read() except Exception as e: print "ERROR: couldn''t read text file: %s" % e finally: contentFile.close() return lookup.get_template("newin.html").render(content=fr) def post(self): try: contentFile = open("static/public/text/en.txt", "r") fd = contentFile.read() except Exception as e: print "ERROR: couldn''t read text file: %s" % e finally: contentFile.close() rety = requests.post(''https://gateway.watsonplatform.net/personality-insights/api/v2/profile'', auth=(''---'', ''''), headers = {"content-type": "text/plain"}, data=fd ) print json.loads(rety.text) return json.loads(rety.text) user_view = MHandler.as_view(''user_api'') app.add_url_rule(''/results2'', view_func=user_view, methods=[''GET'',]) app.add_url_rule(''/results2'', view_func=user_view, methods=[''POST'',])
这是Traceback(请记住上面的结果在打印):
Traceback (most recent call last): File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request response = self.make_response(rv) File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1577, in make_response rv = self.response_class.force_type(rv, request.environ) File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type response = BaseResponse(*_run_wsgi_app(response, environ)) File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app app_rv = app(environ, start_response)
答案1
小编典典Flask只希望视图返回类似响应的对象。
这表示Response
描述主体,代码和标题的,字符串或元组。您正在返回一个dict,这不是其中之一。由于您要返回JSON,因此请返回响应,该响应的正文中包含JSON字符串,内容类型为application/json
。
return app.response_class(rety.content, content_type=''application/json'')
在您的示例中,您已经有一个JSON字符串,即您发出的请求返回的内容。但是,如果要将Python结构转换为JSON响应,请使用jsonify
:
data = {''name'': ''davidism''}return jsonify(data)
在幕后,Flask是一个WSGI应用程序,它希望传递可调用对象,这就是为什么您会收到该特定错误的原因:dict是不可调用的,并且Flask不知道如何将其转换为可调用对象。
Python TypeError:“ str”对象不可用于类
请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。
class One(object):
def __init__(self,class2):
self.name = 'Amy'
self.age = 21
self.class2 = class2
def greeting(self):
self.name = raw_input("What is your name?: ")
print 'hi %s' % self.name
def birthday(self):
self.age = int(raw_input("What is your age?: "))
print self.age
def buy(self):
print 'You buy ',self.class2.name
class Two(object):
def __init__(self):
self.name = 'Polly'
self.gender = 'female'
def name(self):
self.gender = raw_input("Is she male or female? ")
if self.gender == 'male'.lower():
self.gender = 'male'
else:
self.gender = 'female'
self.name = raw_input("What do you want to name her? ")
print "Her gender is %s and her name is %s" % (self.gender,self.name)
Polly = Two()
Amy = One(Polly)
# I want it to print
Amy.greeting()
Amy.buy()
Amy.birthday()
问题代码
Polly.name() # TypeError: 'str' object is not callable
Two.name(Polly)# Works. Why?
为什么在类实例Polly上调用方法无效?我很迷路。我已经看过http://mail.python.org/pipermail/tutor/2003-May/022128.html和其他与此类似的Stackoverflow问题,但我不明白。非常感谢。
python – TypeError:’KFold’对象不可迭代
我到达了需要执行KFold的步骤,以便找到Logistic回归的最佳参数.
以下代码显示在内核本身,但由于某种原因(可能是旧版本的scikit-learn,给我一些错误).
def printing_Kfold_scores(x_train_data,y_train_data): fold = KFold(len(y_train_data),5,shuffle=False) # Different C parameters c_param_range = [0.01,0.1,1,10,100] results_table = pd.DataFrame(index = range(len(c_param_range),2),columns = ['C_parameter','Mean recall score']) results_table['C_parameter'] = c_param_range # the k-fold will give 2 lists: train_indices = indices[0],test_indices = indices[1] j = 0 for c_param in c_param_range: print('-------------------------------------------') print('C parameter: ',c_param) print('-------------------------------------------') print('') recall_accs = [] for iteration,indices in enumerate(fold,start=1): # Call the logistic regression model with a certain C parameter lr = LogisticRegression(C = c_param,penalty = 'l1') # Use the training data to fit the model. In this case,we use the portion of the fold to train the model # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1] lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel()) # Predict values using the test indices in the training data y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values) # Calculate the recall score and append it to a list for recall scores representing the current c_parameter recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) recall_accs.append(recall_acc) print('Iteration ',iteration,': recall score = ',recall_acc) # The mean value of those recall scores is the metric we want to save and get hold of. results_table.ix[j,'Mean recall score'] = np.mean(recall_accs) j += 1 print('') print('Mean recall score ',np.mean(recall_accs)) print('') best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter'] # Finally,we can check which C parameter is the best amongst the chosen. print('*********************************************************************************') print('Best model to choose from cross validation is with C parameter = ',best_c) print('*********************************************************************************') return best_c
我得到的错误如下:
对于这一行:fold = KFold(len(y_train_data),shuffle = False)
错误:
TypeError: init() got multiple values for argument ‘shuffle’
如果我从这一行中删除shuffle = False,我收到以下错误:
TypeError: shuffle must be True or False; got 5
如果我删除5并保持shuffle = False,我收到以下错误;
TypeError: ‘KFold’ object is not iterable
which is from this line:for iteration,start=1):
如果有人可以帮助我解决这个问题,并建议如何使用最新版本的scikit-learn来完成,我们将非常感激.
谢谢.
解决方法
示例代码:
X = np.array([1,1],[2,2,2],[3,3,3],[4,4,4]]) y = np.array([1,4]) # Now you create your Kfolds by the way you just have to pass number of splits and if you want to shuffle. fold = KFold(2,shuffle=False) # For iterate over the folds just use split for train_index,test_index in fold.split(X): X_train,X_test = X[train_index],X[test_index] y_train,y_test = y[train_index],y[test_index] # Follow fitting the classifier
如果你想获得train / test循环的索引,只需添加enumerate
for i,train_index,test_index in enumerate(fold.split(X)): print('Iteration:',i) X_train,y[test_index]
我希望这有效
Python-TypeError:“ int”对象不可调用
给定以下整数和计算
from __future__ import divisiona = 23b = 45c = 16round((a/b)*0.9*c)
结果是:
TypeError: ''int'' object is not callable.
如何将输出舍入为整数?
答案1
小编典典给定以下整数和计算
from __future__ import divisiona = 23b = 45c = 16round((a/b)*0.9*c)
结果是:
TypeError: ''int'' object is not callable.
如何将输出舍入为整数?
我们今天的关于如何修复TypeError:“ int”对象不可迭代?和int对象不可调用怎么解决的分享已经告一段落,感谢您的关注,如果您想了解更多关于Python Flask,TypeError:“ dict”对象不可调用、Python TypeError:“ str”对象不可用于类、python – TypeError:’KFold’对象不可迭代、Python-TypeError:“ int”对象不可调用的相关信息,请在本站查询。
本文标签: