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

时间:2019-04-18 15:18:27

标签: python pandas

我有一个列表:

['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]

8 个答案:

答案 0 :(得分:4)

IIUC,

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

答案 1 :(得分:2)

您这样做:您必须使用条件“或”

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]

答案 2 :(得分:2)

我建议您通过Operators in 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]

答案 3 :(得分: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

答案 4 :(得分:1)

使用[ServiceContract(SessionMode = SessionMode.Allowed)] public interface ICallableForm { [OperationContract] void ShowMessage(); } [DataContract] public class ChatUser { //... [DataMember] public ICallableForm WinForm { get; set; } public override string ToString() { return this.Username; } } class MainForm : Form, ICallableForm { // ... public void ShowMessage() { MessageBox.Show("Hello " + ___clientUser.Username); } // ... private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { int rowIndex = e.RowIndex; ChatMessage message = dataGridView1.Rows[rowIndex+1].Tag as ChatMessage; ChatUser user = message.User; ICallableForm form = user.WinForm; form.ShowMessage(); string str = string.Empty; } 可以提高搜索速度和动态搜索元素数:

set

答案 5 :(得分:1)

您可以使用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]

答案 6 :(得分:0)

=ARRAYFORMULA(PROPER(SUBSTITUTE(IFERROR(REGEXEXTRACT(B:B, 
 "bat|basketball|football|rugby")), 
 "bat", "cricket")))

答案 7 :(得分:0)

使用defaultdict并将列表作为默认列表

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

此时d是什么?

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

并获得'a'或'b'的位置(并证明它适用于'foo'中没有的键incd

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