用键替换python列表元素 [英] Replacing python list elements with key

查看:120
本文介绍了用键替换python列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非唯一字符串列表:

I have a list of non-unique strings:

list = ["a", "b", "c", "a", "a", "d", "b"]

我想用一个唯一标识每个字符串的整数键替换每个元素:

I would like to replace each element with an integer key which uniquely identifies each string:

list = [0, 1, 2, 0, 0, 3, 1]

数字无所谓,只要它是唯一的标识符即可.

The number does not matter, as long as it is a unique identifier.

到目前为止,我所能做的就是将列表复制到集合中,并使用集合的索引来引用列表.我敢肯定还有更好的方法.

So far all I can think to do is copy the list to a set, and use the index of the set to reference the list. I'm sure there's a better way though.

推荐答案

这将确保唯一性,并且ID从0开始是连续的:

This will guarantee uniqueness and that the id's are contiguous starting from 0:

id_s = {c: i for i, c in enumerate(set(list))}
li = [id_s[c] for c in list]

换句话说,您不应使用'list'作为变量名,因为它会遮盖内置类型list.

On a different note, you should not use 'list' as variable name because it will shadow the built-in type list.

这篇关于用键替换python列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆