问题描述
我在Python 2.7中编写了一个代码,其中我定义了一个字符串列表。然后我想要搜索这个列表的元素来获得一组字母。这些字母必须是随机的。即从输入中搜索列表中的每一个字母。
我已经google'ing周围,但我还没有找到一个解决方案。
这是我得到:
wordlist = ['mississippi','miss','lake','que']
letters = str(aqk)
for wordlist中的项目:
如果item.find(字母)!= -1:
打印项目
这是一个例子。这里唯一的输出应该是'湖'和'阙',因为这些词包含一,Q和K。
我该如何重写我的代码才能完成?
感谢您!
Alex
使用:
wordlist = ['mississippi','miss','lake','que']
letters = set('aqk')
wordlist中的单词:
if letters&设置(字):
打印字
输出:
lake
que
注意:&
运算符执行两个集合之间的交集。
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
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.
这篇关于以随机顺序搜索包含特定字母的列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!