Python Forum
Looping through input and using type / isintance to classify it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through input and using type / isintance to classify it
#1
Hi again everyone,
Here is the current problem I am working on.

I have a list of random input:
mixed_list = ['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'xyz', 0, 'blah', 98765., '', 25]

and I have to loop through it to build a dictionary based on the type of input. So strings is a key that returns all strings, etc.

Playing around with the type and isinstance of functons. It seems people prefer isinstance for reasons that are over my head right now (the research I have done talks about concepts about classes and inheritance and things I don't understand yet).

My question is this: I can successfully get the type of input with type but I am having a hard time using a comparative operator on it.

ints = ()
floats = ()
strings =()
for x in mixed_list:
    y = type (x)
    list(y)
I dont really understand how to work after the y = statement. Comparisons like searching for substrings don't seem to work and trying to reformat it as a list also provides an error.

I can provide all the errors and things i have tried if that helps. I have tried probably 3 or 4 ideas that haven't worked. Most have resulted in errors.

for x in mixed_list:
    y = type (x)
    if y == "<class 'int'>":
        print ("found it")
Snipped to try to compare the exact output which fails and prints nothing.

for x in mixed_list:
    y = type (x)
    if "int" in y:
        print ("found it")
Produces error: TypeError: argument of type 'type' is not iterable

for x in mixed_list:
    y = type (x)
    z = str(y)
    if "int" in z:
        print ("found it")
This seems to work. I am not going to delete the thread because I might have more questions and maybe someone can learn from this.
Reply
#2
You can use
if y is type(0):
    ...
Reply
#3
I am only 1.5 weeks into python so hopefully I don't sound like a total moron but in that snippet you mean actually use the number zero or is zero like a placeholder? I am guessing zero is a true false equation?

Here is what i have now and it is no longer returning the actual values or if there is a way to get the values back I don't know how

for x in mixed_list:
    y = type (x)
    #print (y)
    z = str(y)
    if "str" in z:
        strings.append(z)
    elif "int" in z:
        ints.append(z)
    elif "float" in z:
        floats.append(z)
        print (list(floats))

Here is what the output looks like now:

["<class 'float'>"]
["<class 'float'>", "<class 'float'>"]
["<class 'float'>", "<class 'float'>", "<class 'float'>"]

This appears to solve it
for x in mixed_list:
    y = type (x)
    #print (y)
    z = str(y)
    if "str" in z:
        strings.append(x)
    elif "int" in z:
        ints.append(x)
    elif "float" in z:
        floats.append(x)
print (list(floats))
Reply
#4
normally in python we don't check for type. anyway if we have to, we can use type() or isinstance()
>>> a = 1
>>> type(a) is int
True
>>> isinstance(a, int)
True
isinstance() properly handles subclasses and multiple classes
>>> isinstance(1.5, (int, float))
True
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> isinstance(d, dict)
True
https://stackoverflow.com/questions/1549...isinstance
Reply
#5
Here is an alternative implementation
ints, floats, strings = [], [], []
D = {type(0): ints, type(0.0): floats, type(""): strings}
for x in mixed_list:
    D[type(x)].append(x)
print(floats)
Reply
#6
Hey thanks for the help guys. I read the stackoverflow post 4 times previous to posting this. A lot of answers on stackoverflow are over my head at this level. They reference a lot of things I do not understand. I also spent about 25 minutes reading other sites. All equally confusing.

I am trying to now create a dictionary by programmatically looping through the lists I have created. This appears not to be working correctly so I have some misunderstanding of how to add things to a dictionary I guess.

for x in mixed_list:
    y = type (x)
    #print (y)
    z = str(y)
    if "str" in z:
        strings1.append(x)
    elif "int" in z:
        ints1.append(x)
    elif "float" in z:
        floats1.append(x)
for x in strings1:
    sorted_dict['string'] = x
print (sorted_dict)
{'string': ''}

If I indent the print sorted_dict it returns
{'string': 'asdf'}
{'string': 'qwerty'}

I tried using return to get sorted_dict out of there that gave me an error:
SyntaxError: 'return' outside function

I am trying to build my dictionary values programatically by looping through the list.
Reply
#7
I solved this one.

Here is the complete code to solve it:

    for x in mixed_list:
        y = type (x); z = str(y)
        if "str" in z:
            strings1.append(x)
            strings1.sort()
        elif "int" in z:
            ints1.append(x)
            ints1.sort()
        elif "float" in z:
            floats1.append(x)
            floats1.sort
    for x in strings1:
        sorted_dict['Strings'] = (strings1)
    for x in ints1:
        sorted_dict['Integers'] = (ints1)
    for x in floats1:
        sorted_dict['Floats'] = (floats1)
    return sorted_dict
Here is the feedback I got:
1) This can be one line

y = type (x)
z = str(y)
if "str" in z:

2) Do you really need to create the list AND THEN add it to the dictionary? Can you do both in one fell swoop?

for x in floats1:
sorted_dict['Floats'] = (floats1)

3) Do you need to append AND THEN sort each one?

ints1.append(x)
ints1.sort()

Can you sort in the beginning or end?

I understand how to add y & on the same line but I counted figure out how to combine that with the if statement also not sure on the 2rd or 3rd feedback bits.

Any ideas?

This solves the 3rd critique

print(sorted (sorted_dict['Integers']))
print(sorted (sorted_dict['Strings']))
print(sorted (sorted_dict['Floats']))

Ok figured out number 2 also. Just left with how to combine the if statement

sorted_dict={}
def challenge4 ():
    for x in mixed_list:
        y = type (x); z = str(y)
        if "str" in z:
            strings1.append(x)
            sorted_dict['Strings'] = (strings1)
        elif "int" in z:
            ints1.append(x)
            sorted_dict['Integers'] = (ints1)
        elif "float" in z:
            floats1.append(x)
            sorted_dict['Floats'] = (floats1)
    return sorted (sorted_dict)

challenge4()

print(sorted (sorted_dict['Integers']))
print(sorted (sorted_dict['Strings']))

Here is the latest feedback

his doesn't need to appear in two different pieces either:

floats1.append(x)
sorted_dict['Floats'] = (floats1)

Re: sorting - lists must be sorted before you return them (not after). Also think about whether you can do the sorting in one line instead of three....

Sorted doenst seem to work on mutiple list at once.
Reply
#8
So the two challenges I have left is combinging those lines and doing the sort all in one line. Played around with sort and sorted in various places but not getting it to work. More often then not I do not get an error but I don't get a sort either.

Also when I play around with combining lines a lot of times the value returns none.

    for x in mixed_list:
        y = type (x); z = str(y)
        if "str" in z:
            strings1.append(x)
            sorted_dict['Strings'] = (strings1)
        elif "int" in z:
            ints1.append(x)
            sorted_dict['Integers'] = (ints1)
        elif "float" in z:
            #loats1.append(x)
            sorted_dict['Floats'] = floats1.append(x)
Returns: [33, 890, 0, 25]
['asdf', 'qwerty', 'blah', 'zadf', '']
None

As does sorted_dict['Floats'] = (floats1.append(x))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Looping unknowns with user input hw question Turkejive 4 4,991 Sep-30-2018, 04:57 PM
Last Post: Turkejive

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020