How to remove duplicate digits from integers in list
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.