3

I have a list (original_List) that is made up of multiple strings with space in each element as below. How do I create a separate list of the last string (or only file name excluding everything else) of each element from the original list?

Original_List = ['-rw-rw-r-- 1 root root   134801 Nov  2 14:27 aa_base-13.txt', 
'-rw-rw-r-- 1 root root 58630 Nov  2 14:27 aaa_base-extras.txt', 
'-rw-rw-r-- 1 root root   300664 Nov  2 14:27 aaa_base-extras.txt']
Expected output for th new list should be as below:

Extracted_list

['aa_base-13.txt', 'aaa_base-extras.txt', 'aaa_base-extras.txt']
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • This is tricky to do correctly if you need to handle file names that contain spaces. However, parsing the output of `ls` is generally discouraged. Can't you use [`listdir`](https://docs.python.org/3/library/os.html#os.listdir) or [`scandir`](https://docs.python.org/3/library/os.html#os.scandir) instead? – PM 2Ring Nov 10 '16 at 19:14

2 Answers2

5

That's how:

new_list = [x.split()[-1] for x in Original_List]

Please include your attempts in the future when asking questions.

There is no argument passed to split as you can see and that means it takes the default which is the space. Then, the newly created sublists are sliced and just the last item is taken (that's what the [-1] is for). Try removing it to see what it produces.

Of course as most of the times in programming (if not always) there are many ways to do a task. Another for example would be this:

new_list = [y for item in [x.split() for x in Original_List] for y in item if '.' in y]

With this second one you are looking for substrings that contain dots '.'. You could also replace that with '.txt'. That's a more solid way to look for filenames or filenames of a specific extension since they are bound to contain at least one dot.

What the two approaches have in common is that they are list comprehensions. This is a core concept in python and i would suggest looking at it if you are serious about this.

Hope this helps!

Ma0
  • 15,057
  • 4
  • 35
  • 65
2

You can try list comprehension:

[x.split()[-1] for x in Original_List]

Hope this helps!

tomasn4a
  • 575
  • 4
  • 15