繁体   English   中英

如何查找列表中所有出现的多个元素?

[英]How to find all occurrences of multiple elements in a list?

我有一个清单:

['a','b','b','c']

找到我使用的所有元素:

incd=['a','b','b','c']
indeces=[i for i, x in enumerate(incd) if x == 'b']

我如何搜索两个元素及其所有位置?

w1='a'
w2='b'
indeces=[i for i, x in enumerate(incd) if x == w1|w2]

回报

TypeError: unsupported operand type(s) for |: 'str' and 'str'

indeces=[i for i, x in enumerate(incd) if x == 'a|b']

回报

[]

都失败了

我想回来

[0, 1, 2]

IIUC,

s=pd.Series(incd)
s[s.eq(w1)|s.eq(w2)].index
#Int64Index([0, 1, 2], dtype='int64')

你这样做:你必须使用条件'或'

incd = ['a', 'b', 'b', 'c']
w1 = 'a'
w2 = 'b'
indeces = [i for i, x in enumerate(incd) if x == w1 or x== w2]

如果您要测试大量数据:使用列表

w = ['a', 'b' ,'d',...]
indeces = [i for i, x in enumerate(incd) if x in w]

我建议在Python中浏览操作符

替换这个

if x == w1|w2   

有了这个

if x == w1 or x == w2

枚举列表,并检查元素是否等于w1w2

s = ['a','b','b','c']

w1 = 'a'
w2 = 'b'

for indx, elem in enumerate(s):
   if elem == w1 or elem == w2:
      print("Elem: {} at Index {}".format(elem, indx))

输出

Elem: a at Index 0
Elem: b at Index 1
Elem: b at Index 2

更短版本

print([i for i, e in enumerate(s) if e == w1 or e == w2])   # to have a tuple of both elem and indx replace i with (e,i)

输出

[0, 1, 2]

因为你标记了熊猫

l=['a','b','b','c']

s=pd.Series(range(len(l)),index=l)
s.get(['a','b'])
Out[893]: 
a    0
b    1
b    2
dtype: int64

使用一set更高的速度和动态数量的元素来搜索:

find = {2, 3} # The elements we want to find
a = [1,2,2,3,4] # our list
x = [ind for ind, val in enumerate(a) if val in find]
print(x)

您可以in运算符中使用表达式逻辑OR关系。

incd = list('abcd')
w1, w2 = 'a', 'b'

indeces = [i for i, x in enumerate(incd) if x in [w1, w2]]

它可以根据需要产生正确的凹痕

indeces = [0, 1]
indeces=[i for i, x in enumerate(incd) if x == w1 or x == w2]

使用带有列表的defaultdict作为其默认值

from collections import defaultdict
d = defaultdict(list)
for n,e in enumerate(incd): 
    d[e].append(n)

在这一点上有什么?

>>> d
defaultdict(<class 'list'>, {'a': [0], 'b': [1, 2], 'c': [3]})

并获得'a'或'b'的位置(并证明它适用于不在incd的关键'foo'

print( d['a']+d['b']+d['foo'] )
# gives [0,1,2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM