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.
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.
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.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With