python expression
I am new in python, and while reading a BeautifulSoup tutoria开发者_开发问答l, I didn't understand this expression "[x for x in titles if x.findChildren()][:-1]" that i didn't understand? can you explain it
titles = [x for x in titles if x.findChildren()][:-1]
To start with [:-1], this extracts a list that contains all elements except the last element.
>>> a=[1,2,3,4,5]
>>> a[:-1]
[1, 2, 3, 4]
The comes the first portion, that supplies the list to [:-1] (slicing in python)
[x for x in titles if x.findChildren()]
This generates a list that contains all elements (x) in the list "titles", that satisfies the condition (returns True for x.findChildren())
It's a list comprehension.
It's pretty much equivalent to:
def f():
items = []
for x in titles:
if x.findChildren():
items.append(x)
return items[:-1]
titles = f()
One of my favorite features in Python :)
The expression f(X) for X in Y if EXP
is a list comprehension It will give you either a generator (if it's inside ()
) or a list (if it's inside []
) containing the result of evaluating f(X)
for each element of Y
, by only if EXP
is true for that X
.
In your case it will return a list containing every element from titles
if the element has some children.
The ending [:-1]
means, everything from the list apart from the last element.
It's called a for comprehension expression. It is simply constructing a list of all titles in the x
list which return true
when the findChildren
function is called upon them. The final statement substracts the last one from the list.
精彩评论