Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Splitting List That Contains Strings and Integers

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.

like image 557
ayyayyekokojambo Avatar asked Feb 08 '13 16:02

ayyayyekokojambo


People also ask

How do you split text and numbers in Python?

Use the re. split() method to split a string into text and number, e.g. my_list = re. split(r'(\d+)', my_str) .

How do you split multiple elements in a list Python?

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.

How do you split a list of strings into a list in Python?

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.


2 Answers

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]
like image 51
mgilson Avatar answered Nov 03 '22 02:11

mgilson


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']
like image 33
Rohit Jain Avatar answered Nov 03 '22 02:11

Rohit Jain