Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 464
Geet Avatar asked Sep 07 '16 04:09

Geet


People also ask

How do you create a list from a different list in Python?

Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.

Can you make a list of conditions in Python?

Python List Comprehension – Multiple IF Conditions. Python List Comprehension is used to create Lists. While generating elements of this list, you can provide conditions that could be applied whether to include this element in the list.

Can we create a list inside another list?

A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. You can use them to arrange data into hierarchical structures.


2 Answers

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

like image 130
vks Avatar answered Sep 23 '22 21:09

vks


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']
like image 23
Ozgur Vatansever Avatar answered Sep 26 '22 21:09

Ozgur Vatansever