Home > OS >  It sometimes reverse when I turn a string into a set
It sometimes reverse when I turn a string into a set

Time:11-13

The string is: x = 'ABBA'

whenever I use this code: x = 'ABBA' x = ''.join(set(x)) print(x)

It results in: BA but I want it to be the first letters instead of the second letters: AB

Is there any way that I can do it without using reverse function?

CodePudding user response:

Sets in Python are still unordered unfortunately. However, dictionaries in newer versions of Python already preserve insertion order.

You can take advantage of this, by defining a dictionary with empty values, such that you can extract the keys in insertion order:

x = 'ABBA'
x = "".join({k:None for k in x}.keys())
print(x)
# AB

The idea is a bit hacky, but it works for now. Maybe in the future sets will also respect insertion order.

CodePudding user response:

Sets are unordered. so try this.


from collections import Counter


x = 'ABBA'

x = "".join(Counter(x).keys())

print(x) # AB

  • Related