开发者

Python Challenge #2 - For loop problem

Python Challenge #2

Answer I found

FILE_PATH = 'l2-text'
f = open(FILE_PATH)
print ''.join([ t for t in f.read() if t.isalpha()])
f.close()

Question: Why is their a 't' before the for loop t for t in f.read(). I 开发者_运维问答understand the rest of the code except for that one bit. If I try to remove it I get an error, so what does it do?

Thanks.


This is a list comprehension, not a for-loop.

List comprehensions provide a concise way to create lists.

[t for t in f.read() if t.isalpha()]

This creates a list of all of the alpha characters in the file (f). You then join() them all together.

You now have a link to the documentation, which should help you comprehend comprehensions. It's tricky to search for things when you don't know what they're called!

Hope this helps.


[t for t in f.read() if t.isalpha()] is a list comprehension. Basically, it takes the given iterable (f.read()) and forms a list by taking all the elements read by applying an optional filter (the if clause) and a mapping function (the part on the left of the for).

However, the mapping part is trivial here, this makes the syntax look a bit redundant: for each element t given, it just adds the element value (t) to the output list. But more complex expressions are possible, for example t*2 for t ... would duplicate all valid characters.


note the following is also valid:

print ''.join(( t for t in f.read() if t.isalpha()))

instead of [ and ] you have ( and ) This specifies a generator instead of a list. generator comprehension

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜