简体   繁体   English

根据python中的另一个列表匹配列表的元素,其中一个列表的元素是另一个列表的子字符串

[英]match element of a list based on another list in python where elements of one list is the substring of elements of another list

listA = ['abcd754_efgh_20160110_165623.frf', 'abcd754_efghijk_20160110_162419.frf', 'abcd755_mno_20160110_165287.frf', 'abcd755_mnopqr_20160110_164562.frf'  ]
listB = ['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_', 'abcd755_mnopqr_']

I have list A and list B. List A may sometimes have one or 2 elements missing. 我有列表A和列表B。列表A有时可能缺少一个或两个元素。 Based on that I need to create list C with elements in list B by maintaining the same order. 基于此,我需要通过保持相同顺序在列表B中创建元素包含列表C。

I have been unable to find a solution. 我一直找不到解决方案。

You could do something like this: 您可以执行以下操作:

listA = ['abcd754_efgh_20160110_165623.frf', 'abcd754_efghijk_20160110_162419.frf', 'abcd755_mno_20160110_165287.frf']
listB = ['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_', 'abcd755_mnopqr_']
listC = []

for b in listB:
    if any(a.startswith(b) for a in listA):
        listC.append(b)

print listC

outputs ['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_'] 输出['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_']

You didn't specify if you want elements in listB that are or aren't in listA, so add a not before any if you want the other way. 您没有指定是否要让listB中的元素存在于listA中,或者是否不在listA中,因此,如果要使用其他方法,请在any元素之前添加一个not

This is a simple quadratic solution, if you have a lot of elements you'll need something more efficient 这是一个简单的二次方解决方案,如果您有很多元素,则需要更有效的方法

Using a listcomp you can say: 使用listcomp可以说:

listC = [b for b in listB if any(b in a for a in listA)]

For 对于

listA = ['abcd754_efgh_20160110_165623.frf', 'abcd754_efghijk_20160110_162419.frf', 'abcd755_mno_20160110_165287.frf']
listB = ['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_', 'abcd755_mnopqr_']

This prints 此打印

['abcd754_efgh', 'abcd754_efghijk_', 'abcd755_mno_']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM