Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.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_List - Fatal编程技术网

Python在列表中找不到公共元素

Python在列表中找不到公共元素,python,string,list,Python,String,List,我正在用Python3构建一个程序,它需要遍历两个列表,并计算第一个列表中的元素在第二个列表中出现的次数。然而,即使我插入了两个硬编码为具有公共元素的列表,Python也表示该列表没有任何公共元素 以下是我的程序的最低可运行版本: strings = ["I sell","seashells","by the","seashore"] ngramSet = ["by the"] for ngram in ngramSet: print("Ngram: \"" + str(ngram) +

我正在用Python3构建一个程序,它需要遍历两个列表,并计算第一个列表中的元素在第二个列表中出现的次数。然而,即使我插入了两个硬编码为具有公共元素的列表,Python也表示该列表没有任何公共元素

以下是我的程序的最低可运行版本:

strings = ["I sell","seashells","by the","seashore"]
ngramSet = ["by the"]
for ngram in ngramSet:
    print("Ngram: \"" + str(ngram) + "\"")
    # Should return "by the" twice where it appears twice.
    occurrences = [element for element in strings if element is ngram]
    print("Occurrences: " + str(occurrences))
    count = len(occurrences)
    print("Number of times N-gram appears in string" + str(count))
输出:

Ngram: "by the"
Occurrences: []
Number of times N-gram appears in string0
就是为了这个

import collections

strings = ["I sell","seashells","by the","seashore"]
ngramSet = ["by the"]
strings_counter = collections.Counter(strings)

for string in ngramSet:
    print(string, strings_counter[string])
就是为了这个

import collections

strings = ["I sell","seashells","by the","seashore"]
ngramSet = ["by the"]
strings_counter = collections.Counter(strings)

for string in ngramSet:
    print(string, strings_counter[string])

你的方法是正确的。唯一的问题是在
lambda
中,使用
is
比较两个字符串。您应该使用
==
比较它们,因为您正在进行相等比较

你的方法是正确的。唯一的问题是在
lambda
中,使用
is
比较两个字符串。您应该使用
==
比较它们,因为您正在进行相等比较

你可以把它写得简短明了,有多种方法,但这里有一种:

strings = ["I sell","seashells","by the","seashore"]
ngramSet = ["by the"]

# Built in count function
for x in ngramSet:
        print (x, " -> ", strings.count(x))

# Or make it a one-liner
print ([(arg, strings.count(arg)) for arg in ngramSet])

或者你可以简单地使用你的代码,因为它似乎对我有用

你可以把它写得简短明了,有多种方法,但这里有一种:

strings = ["I sell","seashells","by the","seashore"]
ngramSet = ["by the"]

# Built in count function
for x in ngramSet:
        print (x, " -> ", strings.count(x))

# Or make it a one-liner
print ([(arg, strings.count(arg)) for arg in ngramSet])

或者你可以简单地使用你的代码,因为它似乎对我有用

如果您只想获得公共元素,请尝试设置:

list(set(strings).intersection(set(ngramSet)))

如果只想获得公共元素,请尝试使用集合:

list(set(strings).intersection(set(ngramSet)))

首先是通过集合的循环,第二个是通过每个字母的循环。它会为我返回结果。不要使用
is
来比较字符串是否相等,使用
=
is
是用于标识比较首先是通过集合的循环,第二个for循环遍历每个字母。它为我返回结果。不要使用
is
来比较字符串是否相等,使用
=
is
来比较标识这是正确的,但我没有看到lambda这是正确的,但我没有看到lambda