ErAzOr
ErAzOr

Reputation: 57

Check if item of list is in [x][0] of other list with comprehension

this one is driving me crazy. The first list contains filenames without extension. e.g.:

afilenames = [file1, file2, file3]

The second list contains filenames with extensions:

bfiles = [[file1, .exe], [file2, .txt], [file4, ini]]

I know would like to get a list, which returns the files from afilenames, which contains in bfiles.

Expected result:

[file1, file2]

This is my attempt, but it just return bullshit:

[afile for afile in afilenames for bfile in bfiles if afile in bfile[0]]

Upvotes: 0

Views: 37

Answers (2)

Hatatister
Hatatister

Reputation: 1052

This should do what you want

files = [file for file, _ in bfiles if file in afilenames]

Upvotes: 0

ilamaaa
ilamaaa

Reputation: 421

x = [a for a in afilenames for b in bfiles if a == b[0]]

your version also worked for me with the example you provided.

x = [afile for afile in afilenames for bfile in bfiles if afile in bfile]

This also worked.

Upvotes: 0

Related Questions