[英]String contains all the elements of a list
I am shifting to Python, and am still relatively new to the pythonic approach. 我正在转向Python,而且对pythonic方法仍然相对较新。 I want to write a function that takes a string and a list and returns true if all the elements in the list occur in the string.
我想编写一个带字符串和列表的函数,如果列表中的所有元素都出现在字符串中,则返回true。
This seemed fairly simple. 这似乎很简单。 However, I am facing some difficulties with it.
但是,我面临一些困难。 The code goes something like this:
代码如下:
def myfun(str,list):
for a in list:
if not a in str:
return False
return True
Example : myfun('tomato',['t','o','m','a']) should return true
myfun('potato',['t','o','m','a']) should return false
myfun('tomato',['t','o','m']) should return true
Also, I was hoping if someone could suggest a possible regex approach here. 此外,我希望有人可以在这里提出可能的正则表达式方法。 I am trying out my hands on them too.
我也在试试他们。
>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False
def myfun(str,list):
for a in list:
if not a in str:
return False
return True
return true must be outside the for loop, not just after the if statement, otherwise it will return true just after the first letter has been checked. return true必须在for循环之外,而不是在if语句之后,否则它将在检查第一个字母后返回true。 this solves your code's problem :)
这解决了你的代码的问题:)
For each letter you go through the list. 对于每个字母,您都要浏览列表。 So if the list is of length
n
and you have m
letters, then complexity is O(n*m)
. 因此,如果列表长度为
n
并且您有m
字母,则复杂度为O(n*m)
。 And you may achieve O(m)
if you preprocess the word. 如果你预处理这个词,你可以达到
O(m)
。
def myfun(word,L):
word_letters = set(word) #This makes the lookup `O(1)` instead of `O(n)`
return all(letter in word_letters for letter in L)
Also, it's not a good practice to name variables as str
and list
as if you will need later to create list
or use str
, they will be shaded by your variables. 此外,将变量命名为
str
和list
并不是一个好习惯,就像稍后需要创建list
或使用str
,它们将被变量着色。
Some relevant information: 一些相关信息:
If you're not worried about repeat characters, then: 如果您不担心重复字符,那么:
def myfunc(string, seq):
return set(seq).issubset(string)
And, untested, if you do care about repeated characters, then maybe (untested): 并且,未经测试,如果你关心重复的字符,那么可能(未经测试):
from collections import Counter
def myfunc(string, seq):
c1 = Counter(string)
c2 = Counter(seq)
return not (c2 - c1)
For fun, I thought I'd do it with iterators and map: 为了好玩,我想我会用迭代器和地图来做:
from operator import contains
from itertools import imap, repeat
def myfun(str, list):
return all(imap(contains, repeat(str), list))
Then I realised that this essentially does the same thing as the accepted answer, but probably with more method calls. 然后我意识到这基本上和接受的答案一样,但可能有更多的方法调用。
def myfun(str, list):
return all(letter in str for letter in list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.