How to create a list from another list using specific criteria in Python?

How to create a list from another list using python? If I have a list:

input = ['a/b', 'g', 'c/d', 'h', 'e/f'] 

How can I create a list of only those letters that follow the "/" symbol ie

 desired_output = ['b','d','f'] 

The code will be very helpful.

+5
source share
5 answers

You probably have this entry. You can get a simple understanding of the list.

 input = ["a/b", "g", "c/d", "h", "e/f"] print [i.split("/")[1] for i in input if i.find("/")==1 ] 

or

 print [i.split("/")[1] for i in input if "/" in i ] 

Output: ['b', 'd', 'f']

+7
source

With regex:

 >>> from re import match >>> input = ['a/b', 'g', 'c/d', 'h', 'e/f', '/', 'a/'] >>> [m.groups()[0] for m in (match(".*/([\w+]$)", item) for item in input) if m] ['b', 'd', 'f'] 
+2
source

A simple single line can be:

 >> input = ["a/b", "g", "c/d", "h", "e/f"] >> list(map(lambda x: x.split("/")[1], filter(lambda x: x.find("/")==1, input))) Result: ['b', 'd', 'f'] 
+1
source
 >>> input = ["a/b", "g", "c/d", "h", "e/f"] >>> output=[] >>> for i in input: if '/' in i: s=i.split('/') output.append(s[1]) >>> output ['b', 'd', 'f'] 
+1
source

If you fix your list with all the lines encapsulated by "", you can use this to get what you want.

 input = ["a/b", "g", "c/d", "h", "e/f"] output = [] for i in input: if "/" in i: output.append(i.split("/")[1]) print output ['b', 'd', 'f'] 
0
source

All Articles