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

2024-04-26 01:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下列表:

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

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

我尝试在if语句中使用list()命令,检查“Box”中的所有字符是否都在list2内,但似乎要复杂一点。在


Tags: 命令box列表if语句字符list区分
3条回答

我认为内置的join函数可以提供一个有效的解决方案:

>>> list1 = ["Box", "Stall"]
>>> list2 = ["Ball", "Sox"]
>>> def chars_subset(l1, l2):
    s1 = "".join(l1)
    s2 = "".join(l2)
    return not bool([c for c in s2 if c not in s1])

>>> chars_subset(list1, list2)
True
>>> list2 = ["Ball", "Soy"]
>>> chars_subset(list1, list2)
False

这样做怎么样:

  1. 获取list2中所有唯一字符的列表,将其称为charlist
  2. 通读list1,如果list2中的单词中有任何字符不在charlist中,请将它们分开。在

对于第1部分:

>>> charset = set(''.join(i for i in list2))
>>> charset
set(['a', 'B', 'l', 'o', 'S', 'x'])

^{}是不允许重复的特殊类型;每个项都必须是唯一的。在

第2部分:

^{pr2}$

使用一个list comprehension,然后计算结果的长度,我们可以找出charlist中有多少个字母不是来自{}的单词。在

我不认为有一个内置函数可以处理这个问题。你能做的就是

# 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循环。)我将留给您进行分析并确定您是否感兴趣。在

相关问题 更多 >