我正在尝试检查并查看test_list1的每个字符串中是否找到test_list2中的字符串。如果test_list2中存在test_list2中的字符串,那么我想将1添加到新列表中,否则将0添加到同一个新列表中。
所以:
test_list1 = [['Happy', 'Dog'], ['Sad', 'Dog'], ['Dog', 'Dog'], ['Angry', 'Dog']]
test_list2 = ['Happy', 'Sad', 'Angry']
new_list = []
def emotion_detection(x, y):
for i in x:
if i in y:
new_list.append(1)
if i not in y:
new_list.append(0)
print new_list
返回:[0,0,0,0],当我认为它应该返回[1,1,0,1]
提前感谢您的帮助!
答案 0 :(得分:1)
这是你期望的逻辑行为吗?
test_list1 = [['Happy', 'Dog'], ['Sad', 'Dog'], ['Dog', 'Dog'], ['Angry', 'Dog']]
test_list2 = ["Happy", "Sad", "Angry"]
new_list = []
def emotion_detection(x, y):
for i in x:
for string in i:
if string in y:
new_list.append(1)
break
else:
new_list.append(0)
print new_list
答案 1 :(得分:1)
emotions = set(["Happy", "Sad", "Angry"])
sentences = ['Happy Dog', 'Sad Dog', 'Dog Dog', 'Angry Dog']
def is_emotional(sentence):
words = sentence.split()
return bool(emotions.intersection(words))
sentence_emotions = [is_emotional(sentence) for sentence in sentences]
# gives [True, True, False, True]
编辑:Hackaholic对any
有个好主意,但我会把它写成
def is_emotional(sentence):
return any(word in emotions for word in sentence.split())
这可能会更快,特别是对于长句,因为一旦找到情感词,它就会停止。
答案 2 :(得分:0)
test_list1 = [['Happy', 'Dog'], ['Sad', 'Dog'], ['Dog', 'Dog'], ['Angry', 'Dog']]
test_list2 = ["Happy", "Sad", "Angry"]
new_list = []
for element in test_list1:
if element[0] in test_list2:
new_list.append(1)
else:
new_list.append(0)
print new_list
而不是使用i
,请使用i[0]
这是情感的索引!
答案 3 :(得分:0)
尝试这样:
>>> test_list1 = [['Happy', 'Dog'], ['Sad', 'Dog'], ['Dog', 'Dog'],['Angry', 'Dog']]
>>> test_list2 = ["Happy", "Sad", "Angry"]
>>> [any(set(x)&set(test_list2)) for x in test_list1]
[True, True, False, True]
答案 4 :(得分:0)
使用列表推导:
new_list = [k[0] in test_list2 for k in test_list1]