I have this list
names = [ ["cat", 9112, "dog123", 5625], ["luck", 1232, "bad23"] ]
According to this question I have done it by using this code
names = [ ["cat", 9112, "dog123", 5625], ["luck", 1232, "bad23"] ]
new = [[x for x in y if isinstance(x, int)] for y in names]
Output -: [[9112, 5625], [1232]]
Now I want to remove duplicate numbers like this.
expected output -: [[912, 562], [123]]
I was using this code but it wasn't working
m = sorted(list(set(new)))
print(m)
Error -:
Traceback (most recent call last):
File "main.py", line 13, in <module>
m = sorted(list(set(new)))
TypeError: unhashable type: 'list'
Note -: I want to keep only first original digits.(eg -: 1232
need to become 123
not 132
)
A list is mutable; in Python mutable containers are not hashable. set(names)
needs to hash the elements of names
to sort them but your names
list has list as it's elements (["cat", 9112, "dog123", 5625]
and ["luck", 1232, "bad23"]
) and hence, it can't be converted to a set
.
Try this:
names = [ ["cat", 9112, "dog123", 5625], ["luck", 1232, "bad23"] ]
li = [[x for x in y if isinstance(x, int)] for y in names]
final = [["".join(sorted(set(str(x)), key=str(x).index)) for x in y] for y in li]
print(li)
print(final)
It gives the following output:
[[9112, 5625], [1232]]
[['912', '562'], ['123']]
EDIT:
This solution will give the desired result. It may not be best and optimal solution and OP hasn't mentioned anything related to performance.
names = [ ["cat", 9112, "dog123", 5625], ["luck", 1232, "bad23"],["123"] ]
updated_name=[]
for n_list in names:
undated_n_list=[]
for n in n_list:
if type(n)==int:
new_str = []
for digit in str(n):
if digit not in new_str:
new_str.append(digit)
undated_n_list.append(int("".join(map(str, new_str))))
if undated_n_list:
updated_name.append(undated_n_list)
print(updated_name)
Output:
[[912, 562], [123]]
It is bit lengthy but hopefully it works for you.
Here's a function to turn integers into ones with unique digits:
def to_uniq_digit_int(n):
seen = set() # A set that collects seen digits
result = 0
for i in str(n): # A lazy way to iterate over digits in an integer
if i not in seen:
seen.add(i)
# Since we are iterating from the most significant to the least significant, we can multiply the result by ten each time to move the integer one digit left
result = result * 10 + int(i)
return result
Using a helper function may help with readability of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With