Python 数字标签的字符串列表
我有一个字符串列表,需要将其转换为数字标签列表。例如:Python 数字标签的字符串列表,python,string,python-3.x,list,Python,String,Python 3.x,List,我有一个字符串列表,需要将其转换为数字标签列表。例如: x= ['hello', 'John', 'hi', 'John', 'hello', 'pumpum'] # output should be something like this: y=[0, 1, 2, 1, 0, 3] 注意。列表有100K个字符串,我正在从文件中读取它。您可以使用字典: d = {} x= ['hello', 'John', 'hi', 'John', 'hello', 'pumpum'] count = 0
x= ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
# output should be something like this:
y=[0, 1, 2, 1, 0, 3]
注意。列表有100K个字符串,我正在从文件中读取它。您可以使用字典:
d = {}
x= ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
count = 0
for i in x:
if i not in d:
d[i] = count
count += 1
new_x = [d[i] for i in x]
输出:
[0, 1, 2, 1, 0, 3]
如果您有一个大型阵列,则可以使用以下优化方法:
这将返回一个numpy数组,您可以从该数组中执行其他操作,并且与scipy堆栈兼容。下面是一个带有中间字典的简短解决方案:
x = ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
d = dict(zip(set(x),range(len(set(x)))))
y = [d[i] for i in x]
print(y) # [2, 1, 0, 1, 2, 3]
注意:如果您不需要订购数字标签,也就是说,如果您不需要将0关联到x中的第一项,将1关联到x中的第二项,等等,则该功能可以工作
Patrick Artner评论后编辑:
他建议预先计算集合并将其存储为自己的变量,以进行优化,他是对的。以下是更新的代码:
x = ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
s = set(x)
d = dict(zip(s,range(len(s))))
y = [d[i] for i in x]
print(y) # [2, 1, 0, 1, 2, 3]
如果您愿意使用第三方库,您可以使用:
这对我来说是一个非常好的新方法+1@EdChum,谢谢,如果sklearn从根本上依赖np,我不会感到惊讶。它似乎在很多地方都被使用。我很高兴,我喜欢它!您应该预计算集合并将其存储为自己的变量-您正在从每个100k项创建两个集合-一次用于在zip中使用它,一次仅用于获取它的长度,否则为nice one+1Nice!这是唯一与预期idx匹配的解决方案。
x = ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
s = set(x)
d = dict(zip(s,range(len(s))))
y = [d[i] for i in x]
print(y) # [2, 1, 0, 1, 2, 3]
import numpy as np
x = ['hello', 'John', 'hi', 'John', 'hello', 'pumpum']
vals, ids, idx = np.unique(x, return_index=True, return_inverse=True)
print(idx)
array([1, 0, 2, 0, 1, 3], dtype=int64)