如何检查用户输入的单词的字母是否都在列表中? 这似乎不起作用:
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"
答案 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
中(因此只有a
,b
,c
或d
才能使用,使用逆:
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"