【问题标题】:Comparing two lists of strings and getting indices of duplicates比较两个字符串列表并获取重复项的索引
【发布时间】:2015-07-07 14:39:06
【问题描述】:

我想获取重复值(字符串)的索引。 例如:

a=['iii','jjj','rrr']
b=['iii','lll','yyy','ttt','jjj']    
s=numpy.where(a==b)

我希望 s 返回 [0,4],但目前它只返回 [0],因为这是它们在列表中具有相同值和相同位置的位置。

【问题讨论】:

  • 什么是where(),它来自哪里?
  • 另外,[0,4] 的结果如何更有效?两者都出现在索引 0 处,也不出现在索引 4 处。

标签: python arrays string numpy


【解决方案1】:

numpy.wherenumpy.in1d 一起使用:

>>> np.where(np.in1d(b, a))[0]
array([0, 4]

【讨论】:

    【解决方案2】:

    您可以在列表理解中使用 maxmin 函数:

    >>> [i for i,j in enumerate(max(a,b,key=len)) if j in min(a,b,key=len)]
    [0, 4]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多