Reputation: 2575
How can I 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 the list of only those letters that follow slash "/" i.e.
desired_output = ['b','d','f']
A code would be very helpful.
Upvotes: 5
Views: 1243
Reputation: 2286
>>> 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']
Upvotes: 1
Reputation: 9413
Simple one-liner could be to:
>> 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']
Upvotes: 1
Reputation: 52163
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']
Upvotes: 2
Reputation: 641
If you fix your list by having all strings encapsulated by "", you can then 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']
Upvotes: 0
Reputation: 67968
You probably have this input.You can get by simple list comprehension.
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']
Upvotes: 7