Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查列表中的字符串是否存在于其他字符串列表中_Python_String - Fatal编程技术网

Python 检查列表中的字符串是否存在于其他字符串列表中

Python 检查列表中的字符串是否存在于其他字符串列表中,python,string,Python,String,我试图检查并查看test_list2中的字符串是否在test_list1的每个字符串中找到。如果test_list2中的字符串出现在test_list1中,那么我想将1追加到新列表中,否则将0追加到相同的新列表中 因此: 返回:[0,0,0,0],我认为它应该返回[1,1,0,1] 提前感谢您的帮助 test_list1 = [['Happy', 'Dog'], ['Sad', 'Dog'], ['Dog', 'Dog'], ['Angry', 'Dog']] test_list2 = ["Ha

我试图检查并查看test_list2中的字符串是否在test_list1的每个字符串中找到。如果test_list2中的字符串出现在test_list1中,那么我想将1追加到新列表中,否则将0追加到相同的新列表中

因此:

返回:[0,0,0,0],我认为它应该返回[1,1,0,1]

提前感谢您的帮助

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]
,这是情感的索引

这是您期望的逻辑行为吗

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
编辑:Hackaholic对
any
有一个好主意,但我会把它写成

def is_emotional(sentence):
    return any(word in emotions for word in sentence.split())
这可能会更快,尤其是对于长句,因为一旦找到情感词,它就会停止。

尝试如下:

>>> 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]

使用列表理解:

new_list = [k[0] in test_list2 for k in test_list1]

情感检测是如何调用的?请为
x
y
使用有意义的名称。您可以从为函数中的变量指定有意义的名称开始,从x和y开始。例如,其中一个我称之为情感列表,另一个是测试列表。嘿,你和我的方法大致相同,除了
bool和任何
。所以我想知道哪个更快?谢谢!这真的很有帮助。我在以前的相关文章中读到,使用“集合”而不是列表可能有助于与“交集”结合使用,但我不确定如何应用它。这无疑澄清了我的一些误解。应该是
[int(test_list2中的k[0]),而不是test_list1中的k]
,以匹配OP的结果类型。这其实并不重要。
>>> 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]
new_list = [k[0] in test_list2 for k in test_list1]