Separate elements from a list identifying a set of letters

1

First of all, I apologize for the title of the question, which is not clarifying.

I have a list with the names of several files in a folder, of the type: file1_A1, file1_A2, file2_A1, file2_A2, ...

How can I create two lists from this list, one containing all the elements finished with _A1 and one containing all the _A2?

Thank you!

    
asked by Rg111 30.05.2017 в 22:09
source

2 answers

2

If we assume that what you have is a list of chains in this way:

nombres = ['archivo1_A1', 'archivo1_A2', 'archivo2_A1', 'archvio2_A2']

The simplest thing is to use str.endswith :

lista_A1 = [nombre for nombre in nombres if nombre.endswith('_A1')] 
lista_A2 = [nombre for nombre in nombres if nombre.endswith('_A2')]

If all your files end in '_A1' or '_A2' it could be done in a single for .

If you need something more complex because you work with more complex file names, for example, with extension ('file1_A1.py', 'file1_A1.exe', etc) it would be best to use regular expressions.

    
answered by 30.05.2017 / 22:43
source
2

Surely there are better ways, for now it occurs to me is to use list comprehension, a very powerful language technique that allows to transform / filter any list quickly:

lista = [ "archivo1_A1",
          "archivo1_A2", 
          "archivo2_A1", 
          "archvio2_A2"
]

a1 = [a for a in lista if a[-2:] == "A1" ]
a2 = [a for a in lista if a[-2:] == "A2" ]
print("Archivos A1 = {}".format(a1))
print("Archivos A2 = {}".format(a2))

And the exit:

Archivos A1 = ['archivo1_A1', 'archivo2_A1']
Archivos A2 = ['archivo1_A2', 'archvio2_A2']

The structure:

[a for a in lista if a[-2:] == "A1" ]

What it says is:

  • Generate a list []
  • with each element a of the original list a for a in lista
  • And that also have the condition that the last 2 characters are A1 ( if a[-2:] == "A1" )
answered by 30.05.2017 в 22:50