There are two lists, string and query, both containing strings. I want to create a function that returns a 2D array showing:
For example, if we have
As:
So the function should return the array [[3, 2], [1, 3], [1, 2]]
I have tried the following:
def countstuff(string, query)
result = []
for i in query:
array = [[sum(i in j for j in string], len(i)]]
result.append(array)
return result
But before I get to try the function, it returns SyntaxError: invalid syntax.
I can't get my head around this, please help, thank you.
def countstuff(string, query):
result = []
for i in query:
ocr=0
for j in string:
ocr+=j.count(i)
lst=[ocr,len(i)]
result.append(lst)
return result
string = ['om', 'om', 'omg']
query = ['om', 'omg', 'mg']
print(countstuff(string,query))
have fun:)
Simple way to do it:
string = ['om', 'om', 'omg']
query = ['om', 'omg', 'mg']
def countstuff(strings, queries):
result=[]
string = " ".join(strings)
for query in queries:
count= string.count(query)
length = len(query)
result.append([count,length])
return result
print(countstuff(string,query))
Output:
[[3, 2], [1, 3], [1, 2]]
Hi after fiddling some more, I found another solution, thanks everyone.
def countstuff(string, query):
result = []
for i in query:
array = [sum(i in j for j in string)]
array.append(len(i))
result.append(array)
return result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.