Splitting List That Contains Strings and Integers

26,383

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 if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']

Solution 3

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']

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 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]}
Share:
26,383
ayyayyekokojambo
Author by

ayyayyekokojambo

Updated on July 15, 2022

Comments

  • ayyayyekokojambo
    ayyayyekokojambo almost 2 years
    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.

  • mgilson
    mgilson about 11 years
    This works well if the types are known ahead of time and there aren't too many of them :)
  • Donald Duck
    Donald Duck about 7 years
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
  • ViG
    ViG about 6 years
    This answer is incorrect and contains an error. Incorrect because with isdigit() you check whether the element is a string that only contains a number, but does not separate a number from a string (since you can apply it for strings). e.g. the list ['a','b',1,2,3,'10'] will return [2, 3, 4, 5] ['a', 'b'] instead of [1,2,3]['a','b','10']. This brings me to the error: in appending to m you should append ip[x]. Remark, it's better to use len(ip) than hardcoding the length.
  • shray
    shray about 6 years
    I noticed that mistake now because I was using isdigit to return the position of a number in the list. Thanks
  • ViG
    ViG about 6 years
    You still can't distinguish 10 and '10'.
  • shray
    shray about 6 years
    It is because I converted the whole list to a string in order to use isdigit that's why it won't differentiate between them. :)
  • ViG
    ViG about 6 years
    Yes I know that, so you agree that you're not answering OP's question?
  • shray
    shray about 6 years
    Technically I answered his question though it may not satisfy yours. :)
  • ViG
    ViG about 6 years
    Consider the following array that has 3 integers and 2 strings: ip=['a',1,'10',2,3]. Please plug this into your code and tell me how long m and n are.
  • shray
    shray about 6 years
    m has length 4 and n has length 1. I told uh that i convert whole list to string so no diff b/w 10 and '10'.
  • ViG
    ViG about 6 years
    Indeed. This means that the original list, should have had 4 integers and 1 string. But it had 3 integers and 2 strings. Hence your code doesn't split the list correctly. Please change your code so that it is correct, without repeating other answers.
  • Zoe stands with Ukraine
    Zoe stands with Ukraine over 5 years
    @oguzismail wrong. Code-only answers should not be deleted from review
  • oguz ismail
    oguz ismail over 5 years
    @Zoe well, they should be
  • Kanhaiya Agnihotri
    Kanhaiya Agnihotri over 5 years
    please explain @oguzismail
  • mArk
    mArk over 3 years
    Use dtype as float instead of intif the numbers in the list are float values. Otherwise, myIntList will return an empty list.
  • Jeremy Caney
    Jeremy Caney about 2 years
    There are eight existing answers to this question, including a top-voted, accepted answer with sixteen votes. Are you certain your solution hasn't already been given? If not, why do you believe your approach improves upon the existing proposals, which have been validated by the community? Offering an explanation is always useful on Stack Overflow, but it's especially important where the question has been resolved to the satisfaction of both the OP and the community. Help readers out by explaining what your answer does different and when it might be preferred.