在Python清单中寻找模式

时间:2018-08-21 10:15:59

标签: python pattern-matching

我想遍历@Override public void onAccessibilityEvent(AccessibilityEvent event) { final String appPackageName = event.getPackageName().toString(); if (appPackageName.equals("testappone")){ AccessibilityNodeInfo source = getRootInActiveWindow(); processEvent(source); } } private void processEvent(AccessibilityNodeInfo source){ StringBuilder sb = new StringBuilder(); processSubEvent(source, 0, sb); String string = sb.toString(); Log.e(TAG, "String " + string); } private void processSubEvent(final AccessibilityNodeInfo source, final int n, final StringBuilder sb){ sb.append(tools.getText(source)); sb.append("\n"); int childCount = source.getChildCount(); for (int i = 0; i < childCount; i++) { AccessibilityNodeInfo child = source.getChild(i); if (child != null) { processSubEvent(child, n + 1, sb); } child.recycle(); } } 列表和数据分组模式。

实际上,该列表是具有各种属性的字典的列表,可以将其分为3种类型。我将它们称为pythonAB

我正在寻找的模式是每个C类型dict以及前一个A dict和前两个C dict。每个BA字典应仅存在于一组中。

示例:

B

期望的结果:Original List (data): [A1, B1, B2, B3, C1, A2, A3, B4, B5, B6, B7, C2, B8, C3, A4]

条件:

从示例中可以看到,如果没有先前的[[B2,B3,C1,A2], [B7,B8,C3,A4]]A(例如B)或存在另一个C,则应忽略A1AB(例如C)之前的A3。此外,可能还有流氓C也可以忽略(例如C2)。

我尝试过的事情:

# Extract indices for all A elements
As = [i for i, item in enumerate(data) if item['Class']=="A"]

 # Loop through the A's
for a in As:

    # Ensure the A isn't too close to the start of the list to have sufficient prev elements
    if a > 2:

        e = [data[a]]

        # For each prev item
        for index in range (a-1,0,-1):

            # Get the item
            item = data[index]            

            if (len(e) > 3) :
                continue #Exit once there are 4 items in the list 
            elif (len(e) > 1) :
                searching = "B"; # Start by seraching for B's
            else:
                searching = "C"; # After a B is found go to C's

            if item['Class']=="A": # If another A is found before the list is filled end the search
                break
            elif item['Class']==searching:
                e.append(item)


        if data[index]['Class']=="A":
            continue        

这行得通,但是感觉像是很糟糕的代码!任何更好的解决方案建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

在您的情况下,我会使用Regex

import re

# Convert to Class string representation
# example 'ABBBCAABBBBCBCA' 
string_repr = ''.join([item['Class'] for item in data])

# Compile pattern we are looking for
pattern = re.compile(r'BC*B+C+B*A')

# Find last possition of patterns in string_repr
positions = [match.end() - 1 for match in re.finditer(pattern, string_repr)]

# Use indices from positions on data list. Thay match
your_As = [data[i] for i in positions]