簡體   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