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'
Solution 1:
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]
Solution 2:
You can use list comprehension: -
>>>myList = [ 4,'a', 'b', 'c', 1, 'd', 3]>>>myIntList = [x for x in myList ifisinstance(x, int)]>>>myIntList
[4, 1, 3]
>>>myStrList = [x for x in myList ifisinstance(x, str)]>>>myStrList
['a', 'b', 'c', 'd']
Solution 3:
deffilter_by_type(list_to_test, type_of):
return [n for n in list_to_test ifisinstance(n, type_of)]
myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
nums = filter_by_type(myList,int)
strs = filter_by_type(myList,str)
print nums, strs
>>>[4, 1, 3] ['a', 'b', 'c', 'd']
Solution 4:
Split the list according to types found in the orginal list
myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
types = set([type(item) for item in myList])
ret = {}
for typeT inset(types):
ret[typeT] = [item for item in myList iftype(item) == typeT]
>>> ret
{<type'str'>: ['a', 'b', 'c', 'd'], <type'int'>: [4, 1, 3]}
Solution 5:
I'm going to summarize this thread by answering a Python FAQ "how do you write a method that takes arguments in any order, of a narrow range of types?"
Assuming the left-to-right order of all the arguments are not important, try this (based on @mgilson 's answer):
defpartition_by_type(args, *types):
d = defaultdict(list)
for x in args:
d[type(x)].append(x)
return [ d[t] for t in types ]
defcook(*args):
commands, ranges = partition_by_type(args, str, range)
forrangein ranges:
for command in commands:
blah blah blah...
Now you can call cook('string', 'string', range(..), range(..), range(..))
. The argument order is stable, within its type.
# TODO make the strings collect the ranges, preserving order
Post a Comment for "Python - Splitting List That Contains Strings And Integers"