Python 3发生匹配

时间:2015-11-04 06:13:39

标签: python python-3.x match

我开始以一种奇思妙想的方式写这篇文章,而不仅仅是好奇心。我一直在查看可视化工具中的代码,它看起来像我期望的那样迭代但不输出我认为应该的东西。有人能告诉我我错过了什么吗?这只是一个有趣的例子,说明了sql连接表在处理之后的样子。

btnDel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RetailerDatabaseHelper dbHelper = new RetailerDatabaseHelper(TemplateActivity.this);
            final SQLiteDatabase db = dbHelper.getReadableDatabase();
            final CheckBox cb = (CheckBox)findViewById(R.id.checkBox1); //For further investigation!
            Cursor c10 = db.query("Retailer", new String[]{"_id", "name", "validity"}, null, null, "name", null, null, null);
            ListAdapter adapter = new SimpleCursorAdapter(TemplateActivity.this, R.layout.custom_dialog_box, c10, new String[]{"name","validity"}, new int[]{R.id.checkBox1, R.id.number}, 0);
            ListView myList = (ListView) findViewById(R.id.listview);
            myList.setAdapter(adapter);

            if(cb.isChecked())
            {
                Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Not Checked", Toast.LENGTH_SHORT).show();
            }

2 个答案:

答案 0 :(得分:2)

list.index(x)返回值为x的第一项列表中的索引。 所以你应该使用enumerate(b)

def query(a=[1,2,3,4], b=[3,1,1,2,3,4,5,6]):
    for index_a, value_a in enumerate(a):
        for index_b, value_b in enumerate(b):
            if value_a == value_b:
                print("{} {}".format(index_a, index_b))

query()

答案 1 :(得分:1)

对于大型列表,迭代其他列表中每个其他元素的一个列表中的每个元素可能很慢。这是一个二次算法。

这是仅包含列表的解决方案。我将大部分时间用于打印并将结果返回到列表中:

def query_list(a, b):
    res = []
    for index_a, value_a in enumerate(a):
        for index_b, value_b in enumerate(b):
            if value_a == value_b:
                res.append((index_a, index_b))
    return res

这是使用词典的替代实现:

def query_dict(a, b):
    indices = {value: index for index, value in enumerate(a)}
    res = []
    for index_b, value_b in enumerate(b):
        if value_b in indices:
            res.append((indices[value_b], index_b))
    return sorted(res)

生成一些示例数据:

import random
a = list(range(1, 1000))
b = [random.randint(1, 100) for x in range(10000)]

列表版本:

%timeit query_list(a, b)
1 loops, best of 3: 1.09 s per loop

比dict版本慢得多:

%timeit query_dict(a, b)
100 loops, best of 3: 11.8 ms per loop

这大约是10倍。

使用更大的示例数据:

import random
a = list(range(1, 10000))
b = [random.randint(1, 100) for x in range(10000)]

差异变得更加明显:

%timeit query_list(a, b)
1 loops, best of 3: 11.4 s per loop

%timeit query_dict(a, b)
100 loops, best of 3: 13.7 ms per loop

达到接近100的因素。