List Comprehension Examples in Python

The followings are common way to desribe sets in mathematics:

A = {x^2 | x in {0, …, 9}}

B = {1, 2, 4, 8, 16, …, 2^16}

C = {x | x in S and x is odd}

In Python, you can write the above forms by using list comprehension.

The followings are how you can do write the above forms:

1) Handling string list

[‘fox’, ‘fast’]

2) Creates the Pythagorean triples:

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]

3) The following uses a list of strings and produces a list of lists.

[‘THE’, ‘the’, 3]
[‘QUICK’, ‘quick’, 5]
[‘BROWN’, ‘brown’, 5]
[‘FOX’, ‘fox’, 3]
[‘JUMPS’, ‘jumps’, 5]
[‘OVER’, ‘over’, 4]
[‘THE’, ‘the’, 3]
[‘LAZY’, ‘lazy’, 4]
[‘DOG’, ‘dog’, 3]

4) Nested list comprehension

[‘AC’, ‘AD’, ‘BC’, ‘BD’]
[[‘AC’, ‘BC’], [‘AD’, ‘BD’]]

The above nested list comprehension is the same of the following:

[[‘AC’, ‘BC’], [‘AD’, ‘BD’]]

Post Tagged with ,

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

%d 블로거가 이것을 좋아합니다: