0

I'm trying to write this in the most pythonic way possible, but I'm just now learning about lambda's (and what they can be combined with) and I'm having some difficulty.

Using the mechanize module I'm scraping a website for a select control and trying to submit each option value to the form and read the resulting content (maybe I'm trying to do too much for one little 'ol statement). Here is what I've got:

 f = "ctl00$holdSection$selSubAgentFilter" #the select box field name
 self.br.select_form(nr=0) #make the form selection in the browser instance
 #here's where the magic is done
 map( (lambda item,f=f: print(self.br.form.find_control( f ).items[ item[0] ].selected.submit().read() ) ), enumerate( self.br.find_control( f ).items ) )

So, to break it apart, I'm trying to do the following:

  1. iterate over each of the options in the select field, by using enumerate and getting the items from the control and submitting that enumerated list to the map function to basically "walk" over each list item
  2. use a lambda function for the map executed function
  3. submit the items list (enumerated to get indices) to the lambda function
  4. using the enumerate index from the passed item, select the item in the form control and select it
  5. submit the form
  6. read the contents of the new browser window and print() it back to the stdout

Of course in this case the selected property of the chained methods evaluates to a boolean and emits the following error:

AttributeError: 'bool' object has no attribute 'submit'

But you get the idea of what I'm trying to accomplish, I'm just not sure how, and accomplish it with a minimal footprint--I can get it to work using several lines and for loops, I was just trying to stay away from that if possible. I'm trying to branch out and overcome issues in the most pythonic way, rather than the easiest.

Any thoughts?

4

1 回答 1

1

最“Pythonic”的方式是最易读的方式。如果 for 循环对您有用,那么肯定不需要执行 map、filter 或 lambda。

关于何时使用列表推导、映射、过滤器等的一个不错的经验法则是,如果您正在处理数据列表,请使用推导、映射和过滤器。如果您正在执行重复逻辑,例如对列表中的每个项目进行操作,那么您可以执行 for 循环。

示例 1:我需要从列表中过滤掉不必要的数据,所以我做了一个理解。

new_list = [item for item in list if item.has_special_property]

示例 2:我需要为列表中的每个项目运行一些操作,所以我做了一个 for 循环。

for item in list:
    log_important_info(item)

这些显然是简化的示例,但我希望您看到示例 1 适用于数据,而示例 2 适用于代码。

无论如何,我会使用一个for item in option循环,在表单中选择适当的元素,然后提交它,所有这些都在循环中。你和其他任何阅读你的代码的人都会非常清楚你在做什么,尤其是当你评论它的时候。

如果我在项目中遇到它,您上面编写的代码将很难立即理解。

如果您想了解 Pythonic 的真正含义,那么我强烈建议您阅读PEP-8

于 2013-09-14T06:34:25.680 回答