5

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.

2
  • 1
    how did u create such a list?it should give errors Commented Sep 7, 2016 at 4:47
  • This is the list of file names I got using the tar.getmembers(). Commented Sep 7, 2016 at 4:49

5 Answers 5

7

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']

Sign up to request clarification or add additional context in comments.

2 Comments

Oops, sorry. You beat me too it!
@TheLazyScripter u need to be proactive scripter :P
2

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']

Comments

1

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']

Comments

1
>>>  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']

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.