myList = [ 4,'a', 'b', 'c', 1 'd', 3]
how to split this list into two list that one contains strings and other contains integers in elegant/pythonic way?
output:
myStrList = [ 'a', 'b', 'c', 'd' ]
myIntList = [ 4, 1, 3 ]
NOTE: didn't implemented such a list, just thought about how to find an elegant answer (is there any?) to such a problem.
Use the re. split() method to split a string into text and number, e.g. my_list = re. split(r'(\d+)', my_str) .
To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.
Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
As others have mentioned in the comments, you should really start thinking about how you can get rid of the list which holds in-homogeneous data in the first place. However, if that really can't be done, I'd use a defaultdict:
from collections import defaultdict
d = defaultdict(list)
for x in myList:
d[type(x)].append(x)
print d[int]
print d[str]
You can use list comprehension: -
>>> myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
>>> myIntList = [x for x in myList if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']
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