给出以下列表:
list1 = ["Box", "Stall"]
list2 = ["Ball", "Sox"]
如何检查组成“Ball”和“Sox”(“BallSox”)的所有字符是否都包含在“BoxStall”(组成“Box”和“Stall”的字符)中?他们就是这样。必须区分大小写。
我尝试在 if 语句中使用 list()
命令,检查“Box”的所有字符是否都在 list2
内,但看起来似乎是这样必须更复杂一点。
最佳答案
我认为没有内置函数可以处理这个问题。你能做的是
# put all characters of first list into a dictionary
# object. This is easier to use for looking up characters
# later
list_chars = {}
for string in list1:
for char in string:
list_chars[char] = True
# run through second list, for each character
# in the other list, check if it exists in
# the dictionary of characters from the first
# list. If it does not, then set missing_character to True.
missing_character = False
for string in list2:
for char in string:
if not list_chars.get(char,False):
# means that the first list does
# not contain the character char
missing_character = True
# print whether one list was actually missing a character.
if missing_character:
print('Missing some character!')
else
print('Contained all characters!')
如果上述某些部分没有意义,请随时提出后续问题。另外,如果您使用上面的break语句,您可以使上面的代码更快一点。 (如果您已经知道列表缺少一个字符,请尽早退出 for 循环。)我会将其留给您进行推理并确定您是否感兴趣。
关于python - 检查字符串列表中的字符是否是另一个字符串列表中的字符的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12313062/