将for循环转换为列表理解

时间:2017-11-23 08:59:09

标签: python python-2.7 list for-loop list-comprehension

    TextBox txtBox1 = new TextBox();
    private int subItemIndex = 0;
    private ListViewItem viewItem;

    private int? xpos = null;
    private void listView_Click(object sender, EventArgs e)
    {
        xpos = MousePosition.X - listView.PointToScreen(Point.Empty).X;
    } 

    public MainForm()
    {
        InitializeComponent();
        listView.Controls.Add(txtBox1);
        txtBox1.Visible = false;
        txtBox1.KeyPress += (sender, args) =>
        {
            TextBox textBox = sender as TextBox;

            if ((int)args.KeyChar == 13)
            {
                if (viewItem != null)
                {
                    viewItem.SubItems[subItemIndex].Text = textBox.Text;
                }
                textBox.Visible = false;
            }
        };
    }

        private void listView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2 && listView.SelectedItems.Count > 0)
            {
                viewItem = listView.SelectedItems[0];
                var bounds = viewItem.Bounds;
                var col2_bounds = viewItem.SubItems[1].Bounds;
                var col1_bounds = viewItem.SubItems[0].Bounds;
                col1_bounds.Width -= col2_bounds.Width;


                if (xpos > col2_bounds.X)
                {
                    subItemIndex = 1;
                    txtBox1.SetBounds(col2_bounds.X, bounds.Y, col2_bounds.Width, bounds.Height);
                }
                else
                {
                    subItemIndex = 0;
                    txtBox1.SetBounds(col1_bounds.X, bounds.Y, col1_bounds.Width, bounds.Height);
                }
                txtBox1.Text = string.Empty;
                txtBox1.Visible = true;
            }
        }

我已经能够使用以下内容遍历2D数组:

airports = [['BCN','Barcenlona'],['DUB','Dublin']]

code = raw_input().upper()

for i in airports:
    if i[0] == code:
        print i[1]

然而,是否可以使用列表理解来实现相同的效果,例如用户的代码,例如BCN会输出Barcenlona吗?

2 个答案:

答案 0 :(得分:3)

字典 是做事的方式。

In [332]: airports = [['BCN','Barcenlona'],['DUB','Dublin']]

In [333]: dict(airports)
Out[333]: {'BCN': 'Barcenlona', 'DUB': 'Dublin'}

In [334]: mapping = dict(airports)

In [335]: mapping.get('DUB')
Out[335]: 'Dublin'

将数组转换为字典,并使用dict索引与[]dict.get(不抛出KeyError)。

字典的优点在于它在惯用方面更适合您的数据,并且有助于对值进行恒定的O(1)时间查找,如果重复搜索是您的数据的用例,这是理想的。

如果您必须使用2D数组,可以尝试使用next尽可能提高效率:

next((y for x, y in airports if x == code), 'Not Found')

next可以接受两个参数 -

  1. 生成器理解(任何迭代器)
  2. 如果迭代器没有返回任何内容,则返回一个默认参数
  3. 以下是一个快速示例:

    In [336]: next((y for x, y in airports if x == 'DUB'), 'Not Found')
    Out[336]: 'Dublin'
    
    In [337]: next((y for x, y in airports if x == 'XXX'), 'Not Found')
    Out[337]: 'Not Found'
    

    如果没有默认参数,next会抛出一个带有无效密钥的StopIteration

    In [338]: next(y for x, y in airports if x == 'XXX')
    ---------------------------------------------------------------------------
    StopIteration                             Traceback (most recent call last)
    

    请记住,如果没有字典,你无法摆脱O(N)复杂性的陷阱。

答案 1 :(得分:1)

如@ thatrockbottomprogrammer的评论所述,字典会更好。但是如果你仍然想使用列表理解,你可以这样做:

airports = [['BCN','Barcenlona'],['DUB','Dublin']]

code_request = raw_input().upper()

# for i in airports:
#     if i[0] == code:
#         print i[1]

results = [city for (code, city) in airports if code == code_request]