python - 检查字符串列表中的字符是否是另一个字符串列表中的字符的子集

标签 python python-2.7

给出以下列表:

list1 = ["Box", "Stall"]
list2 = ["Ball", "Sox"]

如何检查组成“Ball”和“Sox”(“BallSox”)的所有字符是否都包含在“BoxStall”(组成“Box”和“Stall”的字符)中?他们就是这样。必须区分大小写。

我尝试在 if 语句中使用 list() 命令,检查“B​​ox”的所有字符是否都在 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/

相关文章:

python 将字典数组映射到字典?

python - 导入错误 : No module named 'django.contrib.gis.django'

python - 在 Airflow 中,最终用户可以将参数传递给与某些特定 dag 关联的键

x 轴上的 python/matplotlib 箱线图

python - 使用 Anaconda 在 OS X 上安装 pygraphviz 时出错

Python 3 安装错误。该文件没有关联的程序

python - 如何将嵌套列表作为 Python 中的输入

python-2.7 - 如何从 matplotlib.pyplot 图中的 y 刻度标签中删除负号?

python - 如何访问另一个函数中的函数变量

python - 单个 HTML/页面中的多个交互式图表