user1819786
user1819786

Reputation: 133

Separating list elements in Python

Given the list (listEx) in the following code, I am trying to separate the string and integer and float types, and put them all in their own respective lists. If I want to extract strings only from listEx list, the program should go through listEx, and put the strings in a new list called strList and then print it out to the user. Similarly for integer and float types as well. But if I can just figure out the correct way to do just one, I'll be fine for the others. So far no luck, been at this for an hour now.

listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]
strList=['bcggg'] 

for i in listEx:
    if type(listEx) == str:
        strList = listEx[i]
        print strList[i]
    if i not in listEx:
        break
    else:
        print strList

for i in strList:
    if type(strList) == str:
        print "This consists of strings only"
    elif type(strList) != str:
        print "Something went wrong"
    else:
        print "Wow I suck"

Upvotes: 4

Views: 2791

Answers (5)

unutbu
unutbu

Reputation: 879571

Perhaps instead of if type(item) == ..., use item.__class__ to let the item tell you its class.

import collections
listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]
oftype = collections.defaultdict(list)
for item in listEx:
    oftype[item.__class__].append(item)

for key, items in oftype.items():
    print(key.__name__, items)

yields

int [1, 2, 3, 55]
str ['moeez', 'string', 'another string']
float [2.0, 2.345]

So the three lists you are looking for can be accessed as oftype[int], oftype[float] and oftype[str].

Upvotes: 3

raton
raton

Reputation: 428

     python 3.2
     listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]

     strList = [ i for i in listEx if type(i) == str ] 
     ## this is list comprehension ##

     ###  but you can use conventional ways.

     strlist=[]                   ## create an empty list.          
     for i in listex:             ## to loop through the listex.
             if type(i)==str:     ## to know what type it is
                    strlist.append(i)        ## to add string element
     print(strlist)    



     or:
     strlist=[]
     for i in listex:
            if type(i)==str:
                strlist=strlist+[i]

     print(strlist)  

Upvotes: -1

alinsoar
alinsoar

Reputation: 15793

integers = filter(lambda x: isinstance(x,int), listEx)

strings = filter(lambda x: isinstance(x,str), listEx)

and so on...

Upvotes: 2

abought
abought

Reputation: 2680

Python for loops iterate over actual object references. You may be seeing strange behavior partly because you're giving the object reference i where a numerical list index should go ( the statement listEx[i] makes no sense. Array indices can be values of i = 0...length_of_list, but at one point i="moeez")

You're also replacing the whole list every time you find an item (strList = listEx[i]). You could instead add a new element to the end of the list using strList.append(i), but here's a more concise and slightly more pythonic alternative that creates the entire list in one line using a very useful python construct called list comprehensions.

listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]
strList = [ i for i in listEx if type(i) == str ] 

Gives:

print strList
>>> print strList
['moeez', 'string', 'another string']

For the rest,

>>> floatList = [ i for i in listEx if type(i) == float ] 
>>> print floatList
[2.0, 2.345]

>>> intList = [ i for i in listEx if type(i) == int ] 
>>> intList
[1, 2, 3, 55]

>>> remainders = [ i for i in listEx 
    if ( ( i not in  strList ) 
          and (i not in  floatList ) 
          and ( i not in intList) )  ]
>>> remainders
[]

Upvotes: 1

pydsigner
pydsigner

Reputation: 2885

Simply change type(strList) and type(listEx) to type(i). You are iterating over the list, but then checking whether or not the list is a string, not whether or not the item is a string.

Upvotes: 2

Related Questions