简体   繁体   English

通过理解检查列表项是否在其他2D列表中丢失

[英]Check if item of list is missing in other 2D list with comprehension

The first list contains filenames with extensions: 第一个列表包含带有扩展名的文件名:

afiles = [['file1', '.exe'], ['file2', '.txt']]

The second list contains filenames without extension. 第二个列表包含不带扩展名的文件名。 eg: 例如:

bfiles = ['file1', 'file2', 'file3', 'file4']

I know want to know which files of bfiles are missing in afiles. 我知道想知道afile中缺少bfile的哪些文件。 The expected result should be: 预期结果应为:

['file3', 'file4']

I'd like to realize this with comprehension. 我想领悟到这一点。

You could just try this simple list comprehension :) 您可以尝试这种简单的列表理解方法:)

>>> afiles = [['file1', '.exe'], ['file2', '.txt']]
>>> bfiles = ['file1', 'file2', 'file3', 'file4']
>>> [x for x in bfiles if x not in (y[0] for y in afiles)]
['file3', 'file4']

or better, you could just assign the afiles files without extensions like, 或者更好的是,您可以仅分配afiles文件,而无需扩展名,

>>> afiles_names = [x[0] for x in afiles]
>>> [x for x in bfiles if x not in afiles_names] # so you won't have to compute that each time
['file3', 'file4']

Just check if items of bfiles fail to be found in any zero indexes in afiles. 只需检查bfile的项目是否在afile的任何零索引中都找不到。

afiles = [['file1', '.exe'], ['file2', '.txt']]
bfiles = ['file1', 'file2', 'file3', 'file4']

result = [file for file in bfiles if not any(file == afile[0] for afile in afiles)]
['file3', 'file4']

List-comprehension with itertools.chain : 使用itertools.chain列表理解:

from itertools import chain

afiles = [['file1', '.exe'], ['file2', '.txt']]
bfiles = ['file1', 'file2', 'file3', 'file4']

print([x for x in bfiles if x not in chain.from_iterable(afiles)])
# ['file3', 'file4']

You can use the set method difference() : 您可以使用set方法difference()

set(bfiles).difference(i[0] for i in afiles)
# {'file4', 'file3'}

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

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