我有一个非唯一字符串列表:
list = ["a", "b", "c", "a", "a", "d", "b"]
我想用一个唯一标识每个字符串的整数键替换每个元素:
list = [0, 1, 2, 0, 0, 3, 1]
只要数字是唯一标识符,该数字无关紧要。
到目前为止,我所能想到的就是将列表复制到一个集合中,并使用集合的索引来引用列表。我确信有更好的方法。
答案 0 :(得分:10)
这将保证唯一性,并且id从0
开始是连续的:
id_s = {c: i for i, c in enumerate(set(list))}
li = [id_s[c] for c in list]
另外,您不应将'list'
用作变量名称,因为它会影响内置类型list
。
答案 1 :(得分:5)
以下是defaultdict的单通解决方案:
from collections import defaultdict
seen = defaultdict()
seen.default_factory = lambda: len(seen) # you could instead bind to seen.__len__
In [11]: [seen[c] for c in list]
Out[11]: [0, 1, 2, 0, 0, 3, 1]
这是一种伎俩但值得一提!
替代方案suggested by @user2357112 in a related question/answer,将以itertools.count
递增。这允许您只在构造函数中执行此操作:
from itertools import count
seen = defaultdict(count().__next__) # .next in python 2
这可能更合适,因为default_factory方法在全局范围内不会查找seen
。
答案 2 :(得分:4)
>>> lst = ["a", "b", "c", "a", "a", "d", "b"]
>>> nums = [ord(x) for x in lst]
>>> print(nums)
[97, 98, 99, 97, 97, 100, 98]
答案 3 :(得分:2)
如果你不挑剔,那么使用哈希函数:它返回一个整数。对于相同的字符串,它返回相同的哈希:
li = ["a", "b", "c", "a", "a", "d", "b"]
li = map(hash, li) # Turn list of strings into list of ints
li = [hash(item) for item in li] # Same as above
答案 4 :(得分:1)
功能性方法:
l = ["a", "b", "c", "a", "a", "d", "b", "abc", "def", "abc"]
from itertools import count
from operator import itemgetter
mapped = itemgetter(*l)(dict(zip(l, count())))
您还可以使用简单的生成器函数:
from itertools import count
def uniq_ident(l):
cn,d = count(), {}
for ele in l:
if ele not in d:
c = next(cn)
d[ele] = c
yield c
else:
yield d[ele]
In [35]: l = ["a", "b", "c", "a", "a", "d", "b"]
In [36]: list(uniq_ident(l))
Out[36]: [0, 1, 2, 0, 0, 3, 1]