如何在python2.7中的函数中发送变量
问题描述:
我在Python2.7中编写,需要弄清楚如何在调用方向时发送“>”变量。我需要多次调用这个函数,有时它需要是“<”。如何在python2.7中的函数中发送变量
sentiment_point = giving_points(index_focus_word, 1, sentence, -2)
def giving_points(index_focus_word, index_sentiment_word, sentence, location):
if index_focus_word > index_sentiment_word:
sentiment_word = sentence[index_focus_word + location]
我试着在下面显示我想要做什么,但它不起作用。
sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2)
def giving_points(index_focus_word, sign, index_sentiment_word, sentence, location):
if index_focus_word sign index_sentiment_word:
sentiment_word = sentence[index_focus_word + location]
答
sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2)
... if index_focus_word sign index_sentiment_word:
这是行不通的,因为你是路过“>”作为一个简单的字符串和Python不承认你打算把它作为一个运营商。
如果你的问题是二进制(“<”或‘>’)一个非常简单的解决办法是,通过不是一个字符串,但一个布尔值,以确定使用哪个运营商:
sentiment_point = giving_points(index_focus_word, True, 1, sentence, -2)
def giving_points(index_focus_word, greater, index_sentiment_word, sentence, location):
if greater:
if index_focus_word > index_sentiment_word:
sentiment_word = sentence[index_focus_word + location]
else: #....
else:
if index_focus_word < index_sentiment_word:
答
的operator
模块提供了实现Python操作符的函数。在这种情况下,你想要operator.gt
。
import operator
sentiment_point = giving_points(index_focus_word, operator.gt, 1, sentence, -2)
def giving_points(index_focus_word, cmp, index_sentiment_word, sentence, location):
if cmp(index_focus_word, index_sentiment_word):
sentiment_word = sentence[index_focus_word + location]
+0
这是完美的,非常感谢你@chepner –
请格式化您的代码,方法是突出显示它并按下内嵌编辑器顶部的“{}”。 – Oisin