简体   繁体   中英

Check if two unordered sequence are equal

I'm looking for an easy (and quick) way to determine if two unordered sequence contain the same elements:

For example:

GTTUIP and EGTP 
return [[0,1],[1,2],[2,2],[5,3]]

Any function in python .

The following comprehensions will do:

s1, s2 = 'GTTUIP', 'EGTP'

i2 = {char: i for i, char in reversed(list(enumerate(s2)))}
# {'P': 3, 'G': 1, 'T': 2, 'E': 0}

[[i, i2[char]] for i, char in enumerate(s1) if char in i2]
# [[0, 1], [1, 2], [2, 2], [5, 3]]

The former creates a lookup mapping from characters to their indexes in the second sequence. The reversed in there is to ensure we map to the index of each char's first occurrence. The latter builds the final structure by iterating the first sequence and looking up the indexes from the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM