Reputation: 31
Please help. I have in input script the differing values and what need only remove the same values.
I do this but there is didn't check the type of value and only just didn't find it.
Example :
import sys
def clean_list(list_to_clean):
c = []
c = list(set(list_to_clean))
return c
c= clean_list(sys.argv[1:])
print c
or
import sys
def clean_list(list_to_clean):
c = []
for i in list_to_clean:
if i not in c:
c.append(i)
return c
c= clean_list(sys.argv[1:])
print c
so my problem, when i in input send values :
'asd', 'dsa', 1, '1', 1.0
it was back :
['asd', 'dsa', 1, '1']
but need :
['asd', 'dsa', 1, '1', 1.0]
Thanks
Upvotes: 2
Views: 166
Reputation: 371
Since int 1 and float 1.0 hash to the same value, you need to retain some more information about the object -- it's 'type' is the best candidate here. You can do this in a one liner if you want:
>>> seq = ['asd', 'dsa', 1, '1', 1.0, 'asd', 'dsa', 1]
>>> [pair[1] for pair in {(type(obj), obj,) for obj in seq}]
['asd', 'dsa', 1, 1.0, '1']
Breaking it down a bit more, the set comprehension:
pairs = {(type(obj), obj,) for obj in seq}
Retains the type of obj in a tuple so it's not lost. Then the list comprehension just gets back the value (not the type):
final_answer = [pair[1] for pair in pairs]
As an aside, you can use the builtin hash
function to see what value python will use for dictionary/set hashing:
>>> hash(1.0)
1
>>> hash(1)
1
This is spelled out in the docs -- in fact, they mention the very case of 1 and 1.0.
Upvotes: 4
Reputation: 311
Python automatically shortens the integer and, when the cleaning code sees it, it thinks it is a duplicate. Try storing it as a string '1.0'
and then converting it back to an integer for usage using the int
function.
Upvotes: 0