如何检查输入的字母是否在列表中?

时间:2015-01-30 13:44:16

标签: python list python-2.7

如何检查用户输入的单词的字母是否都在列表中? 这似乎不起作用:

letters = ["a","b","c","d"]
inpt = str(raw_input())
if list(inpt) in letters:
    print "letters are in list"
else:
    print "letters are not in list"

2 个答案:

答案 0 :(得分:4)

使用sets;测试交叉点或子集:

if set(inpt) & set(letters):
    # *some* letters are in inpt

if set(letters) <= set(inpt):
    # *all* letters are in inpt

或者您希望inpt中的所有字符都在letters中(因此只有abcd才能使用,使用逆:

if set(inpt) <= set(letters):
    # *all* of inpt is in letters

演示:

>>> letters = ['a', 'b', 'c', 'd']
>>> inpt = 'the quick brown fox jumped over the lazy dog'
>>> set(letters) & set(inpt)
{'d', 'c', 'a', 'b'}
>>> set(letters) <= set(inpt)
True
>>> inpt = 'no letters in use!'
>>> set(letters) & set(inpt)
set()
>>> set(letters) <= set(inpt)
False
>>> inpt = 'abbacac'
>>> set(inpt) <= set(letters)
True

如果在set()语句中使用空if时将其视为false,则认为非空set()为真。

答案 1 :(得分:4)

例如这样?

letters = set(["a","b","c","d"])
inpt = raw_input()
if set(inpt).issubset(letters):
    print "letters are in list"
else:
    print "letters are not in list"

比照Python - verifying if one list is a subset of the other