Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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

Here goes your solution:

for item in wordlist:
  b = False
  for c in letters:
    b = b | (item.find(c) != -1)
  if b:
    print item
[word for word in wordlist if any(letter in word for letter in 'aqk')]

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top