python-3.x 检查列表中的项目是否在另一个列表的项目中

k10s72fa  于 2023-03-20  发布在  Python
关注(0)|答案(3)|浏览(126)
list_a = ['one', 'two', 'three', 'four', 'cat', 'dog', 'house', 'Spain', 'India', 'Portugal']

list_b = ['PortugalSpainIndiahousefourtwo', 'fivesixseveneight', 'nineteneleventwelve', 'JapanBrazilthirtyseventeen']

给定list_a和list_B,如何检查list_b中的项是否由list_a中的元素组成?
我试着按照python代码,但没有得到正确的结果。

final_list = []

for x in list_a:
   for y in list_b:
      if x in y:
         y_update = y.replace(x, '')
         final_list.append(y_update)
      else: 
         final_list.append(y)

所需的输出应为final_list:['', 'fivesixseveneight', 'nineteneleventwelve', 'JapanBrazilthirtyseventeen']

siv3szwd

siv3szwd1#

list_a = ['one', 'two', 'three', 'four', 'cat', 'dog', 'house', 'Spain', 'India', 'Portugal', 'hello', 'world']
list_b = ['PortugalSpainIndiahousefourtwo', 'fivesixseveneight', 'nineteneleventwelve', 'JapanBrazilthirtyseventeen']
matching_list = []

for b in list_b:
    search = b
    for a in list_a:
        if a in b:
            b = b.replace(a, '')
        if b == "":
            matching_list.append(search)
            break
print(matching_list)

不匹配列表print(set(list_b).difference(set(matching_list)))

qzwqbdag

qzwqbdag2#

您可以通过将单词替换为相应数量的占位符字符(例如'*')来创建匹配位置的模式。如果字符串中的所有位置都至少替换了一次,则整个字符串由list_a中的单词组成。

list_a = ['one', 'two', 'three', 'four', 'cat', 'dog', 'house',
          'Spain', 'India', 'Portugal']
list_b = ['PortugalSpainIndiahousefourtwo', 'fivesixseveneight',
          'nineteneleventwelve', 'JapanBrazilthirtyseventeen']

r = [b for b in list_b
     if all("*" in z for z in zip(*(b.replace(a,"*"*len(a)) for a in list_a)))]

print(r)
['PortugalSpainIndiahousefourtwo']

要在此示例中说明“PortugalSpainIndiahousefourtwo”:

one      PortugalSpainIndiahousefourtwo # 1
two      PortugalSpainIndiahousefour*** # 2
three    PortugalSpainIndiahousefourtwo # 3
four     PortugalSpainIndiahouse****two # 4
cat      PortugalSpainIndiahousefourtwo # 5
dog      PortugalSpainIndiahousefourtwo # 6
house    PortugalSpainIndia*****fourtwo # 7
Spain    Portugal*****Indiahousefourtwo # 8
India    PortugalSpain*****housefourtwo # 9
Portugal ********SpainIndiahousefourtwo # 0
         ||||||||||||||||||||||||||||||
         vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
matched: 000000008888899999777774444222  <- all positions have at least one *
  • 注意,当字符串由单词覆盖自身形成时,这将不会检测自重叠单词,例如“edited”:'编辑'*
qltillow

qltillow3#

关于str.replace()函数有一点:如果没有找到搜索字符串,它将返回原始字符串。记住这一点,代码非常简单:

final_list = []
for word in list_b:
    for sub_word in list_a:
        word = word.replace(sub_word, "")
    final_list.append(word)

相关问题