【问题标题】:python: replace list items with index of items in another listpython:用另一个列表中的项目索引替换列表项目
【发布时间】:2018-07-09 18:50:45
【问题描述】:

我有 2 个列表,例如说

list1 = ['abc', 'xyz', 'cat', 'xyz', 'abc', 'pqr', 'dog']
list2 = ['xyz', 'dog', 'pqr', 'abc', 'cat']

我想通过将list1 替换为list2 中元素的索引来创建一个新列表

list3 = [3, 0, 4, 0, 3, 2, 1]

我应该在这里提一下,我实际上是从list1 得到list2

list2 = list(set(list1))

所以list2 没有重复项,并且拥有list1 的所有元素。

我想知道以 python 方式获得list3 的最快方法。 到目前为止,我已经尝试了两种方法:

1>基本.index方式

list3 = [list2.index(item) for item in list1]

2> 使用以元素为键、索引为值的字典

d = {list2[i]:i for i in range(len(list2))}
list3 = [d[item] for item in list1]

【问题讨论】:

  • 你应该包括你的两次尝试,这样我们就不会给你重复的答案。
  • 我相信唯一比 [list2.index(i) for i in list1] 更好的方法是通过将已查找值的索引存储在哈希表中来执行类似“动态编程”的方法
  • 我会去字典路线。您可以像 d = {x: i for i, x in enumerate(list2)} 那样构建您的查找字典。
  • 注意list2 中元素的顺序是随机的,因为set()(集合是无序的)。因此list3 中的索引不可靠,并且可以在会话之间更改。这就提出了一个问题,你的最终目标是什么?

标签: python python-3.x list indexing


【解决方案1】:

如果您担心查找重复值,只需先创建索引:

>>> idx={e:list2.index(e) for e in list2}

或者:

>>> idx={e:n for n,e in enumerate(list2)}

然后:

>>> [idx[e] for e in list1]
[3, 0, 4, 0, 3, 2, 1]

【讨论】:

  • 为什么不直接使用第二个选项呢?第一个比直接在列表理解中进行 index 查找快一点。
【解决方案2】:
idx = dict(zip(list2, range(len(list2))))
list(map(idx.get, list1))
# [3, 0, 4, 0, 3, 2, 1]

【讨论】:

    猜你喜欢
    • 2022-07-18
    • 2019-12-24
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2012-11-11
    • 1970-01-01
    相关资源
    最近更新 更多