How to get ordered set? [duplicate]

大兔子大兔子 提交于 2020-01-30 12:11:27

问题


EDIT: Thanks. I assumed sets were ordered since the output is almost in alphabetical order. But yes I want an ordered set.

def create_table(secret):    
    sec = set(secret) 
    alpha = set("abcdefghiklmnopqrstuvwxyz")
    bet = alpha - sec

    newSecret = secret & bet

    print newSecret



 OUTPUT:  set(['A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z'])

How do I create an ordered set?

Example: If I take the string "mathematics" and the string "abcdefghiklmnopqrstuvwxyz", essentially the new string should be "MATHEICSBDFGKLNOPQRUVWXYZ" (assuming i have the code to uppercase the string). There is no 'J' in this string so it isn't a typo.

I'm trying to take the unique characters from the variable 'secret' and unique characters from the variable 'alpha' and get ordered unique characters from both.


回答1:


Python doesn't have an OrderedSet; usually we fake it with an OrderedDict.

For example:

>>> from collections import OrderedDict
>>> s = "mathematics"
>>> alpha = "abcdefghiklmnopqrstuvwxyz"
>>> d = OrderedDict.fromkeys(s+alpha)
>>> d
OrderedDict([('m', None), ('a', None), ('t', None), ('h', None), ('e', None), ('i', None), ('c', None), ('s', None), ('b', None), ('d', None), ('f', None), ('g', None), ('k', None), ('l', None), ('n', None), ('o', None), ('p', None), ('q', None), ('r', None), ('u', None), ('v', None), ('w', None), ('x', None), ('y', None), ('z', None)])
>>> ''.join(d)
'matheicsbdfgklnopqruvwxyz'

This doesn't quite work as well as an OrderedSet would, but is often close enough for government work.




回答2:


It sounds like you want an ordered set, ordered by the first occurrence of the item within the first string, or (for items not present in the first string) the first occurrence of the item within the second string.

Easiest thing to do is to have a set, and an string. Iterate over the first string; for each item, if it's not in the set, add it to the set and append it to the string. Then do the same for the second string.



来源:https://stackoverflow.com/questions/19499989/how-to-get-ordered-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!