Search strings in list containing specific letters in random order

元气小坏坏 提交于 2019-11-27 02:58:58

问题


I am writing a code in Python 2.7 in which I have defined a list of strings. I then want to search this list's elements for a set of letters. These letters must be in random order. i.e. search the list for every single letter from input. I have been google'ing around but i haven't found a solution.

Here's what i got:

wordlist = ['mississippi','miss','lake','que']

letters = str(aqk)

for item in wordlist:
    if item.find(letters) != -1:
        print item

This is an example. Here the only output should be 'lake' and 'que' since these words contain 'a','q' and 'k'. How can I rewrite my code so that this will be done?

Thanks in advance!

Alex


回答1:


It would be easy using set():

wordlist = ['mississippi','miss','lake','que']

letters = set('aqk')

for word in wordlist:
    if letters & set(word):
        print word

Output:

lake
que

Note: The & operator does an intersection between the two sets.




回答2:


for item in wordlist:
    for character in letters:
        if character in item:
            print item
            break



回答3:


Here goes your solution:

for item in wordlist:
  b = False
  for c in letters:
    b = b | (item.find(c) != -1)
  if b:
    print item



回答4:


[word for word in wordlist if any(letter in word for letter in 'aqk')]



回答5:


Using sets and the in syntax to check.

wordlist = ['mississippi','miss','lake','que']

letters = set('aqk')

for word in wordlist:
   if word in letters:
       print word


来源:https://stackoverflow.com/questions/9443302/search-strings-in-list-containing-specific-letters-in-random-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!