I am new to python and was reading through some code for a Sublime Text plugin and came across some code I am not familiar with.

views = [v for v in sublime.active_window().views()]

it is the "[v for v" part that I don't understand. What in the heck is this piece of code doing?

Thanks in advance!

有帮助吗?

解决方案 2

This is a list comprehension. It's a bit like an expression with an inline for loop, used to create a quick list on the fly. In this case, it's creating a shallow copy of the list returned by sublime.active_window().views().

List comprehensions really shine when you need to transform each value. For example, here's a quick list comprehension to get the first ten perfect squares:

[x*x for x in range(1,11)]

其他提示

That's a list comprehension. It is equivalent to (but more efficient than):

views = []
for v in sublime.active_window().views():
    views.append(v)

Note that in this case, they should have just used list:

views = list(sublime.active_window().views())

There are other types of comprehensions that were introduced in python2.7:

set comprehension:

{x for x in iterable}

and dict comprehension:

{k:v for k,v in iterable_that_yields_2_tuples}

So, this is an inefficient way to create a dictionary where all the values are 1:

{k:1 for k in ("foo","bar","baz")}

Finally, python also supports generator expressions (they're available in python2.6 at least -- I'm not sure when they were introduced):

(x for x in iterable)

This works like a list comprehension, but it returns an iterable object. generators aren't particularly useful until you actually iterate over them. The advantage is that a generator calculates the values on the fly (rather than storing the values in a list which you can then iterate over later). They're more memory efficient, but they execute slower than list-comps in some circumstances -- In others, they outshine list-comprehensions because it's easy to say -- Just give me the first 3 elements please -- whereas with a list comprehension, you'd have to calculate all the elements up front which is sometimes an expensive procedure.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top