Python - a separation list containing strings and integers

myList = [ 4,'a', 'b', 'c', 1 'd', 3]

how to split this list into two lists that contain strings and the others are integers in an elegant / pythonic style?

output:

myStrList = [ 'a', 'b', 'c', 'd' ]

myIntList = [ 4, 1, 3 ]

NOTE: such a list was not implemented, just thought about how to find an elegant answer (are there any?) To such a problem.

+5
source share
8 answers

As mentioned in the comments, you should start thinking about how you can get rid of the list in which homogeneous data is stored first. However, if this is really impossible to do, I would use defaultdict:

from collections import defaultdict
d = defaultdict(list)
for x in myList:
   d[type(x)].append(x)

print d[int]
print d[str]
+13
source

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']
+9
source
def filter_by_type(list_to_test, type_of):
    return [n for n in list_to_test if isinstance(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']
+3

,

myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
types = set([type(item) for item in myList])
ret = {}
for typeT in set(types):
    ret[typeT] = [item for item in myList if type(item) == typeT]

>>> ret
{<type 'str'>: ['a', 'b', 'c', 'd'], <type 'int'>: [4, 1, 3]}
+2

, FAQ Python: " , ?"

, - , ( @mgilson):

def partition_by_type(args, *types):
    d = defaultdict(list)

    for x in args:
        d[type(x)].append(x)

    return [ d[t] for t in types ]

def cook(*args):
    commands, ranges = partition_by_type(args, str, range)

    for range in ranges:
        for command in commands:
            blah blah blah...

cook('string', 'string', range(..), range(..), range(..)). .

# TODO  make the strings collect the ranges, preserving order
0

isdigit(), .

ip=['a',1,2,3]
m=[]
n=[]
for x in range(0,len(ip):
    if str(ip[x]).isdigit():
        m.append(ip[x])
    else:n.append(ip[x])
print(m,n)
0
n = (input("Enter  string and digits: "))
d=[]
s=[]
for  x in range(0,len(n)):
    if str(n[x]).isdigit():
        d.append(n[x])
    else
        s.append(n[x])
print(d)
print(s)
0
import strings;
num=strings.digits;
str=strings.letters;
num_list=list()
str_list=list()
for i in myList:
    if i in num:
        num_list.append(int(i))
    else:
        str_list.append(i)
-1

All Articles