Python comprehension

at first

Please note that you do not have vocabulary.

What is a comprehension?

Lists can be defined with a small number of lines using comprehension notation. For example, when adding elements from 0 to 99

No1(Not included).py


intlist1=list()
for i in range(100):
    intlist1.append(i)

It takes 3 lines, but in the comprehension notation

No1(Comprehension notation).py


intlist=[n for n in range(100)]

It takes only one line. How are you interested?

Basic syntax

Well, first of all, the basic syntax. [** Last element to add ** for ** counter ** in ** iterable **] Write. To explain the list of elements that have values from 0 to 99

Commentary.py


intlist=[i for i in range(100)]
#[0,1,2,3,4,5,...97,98,99]

The value of i is 0 to 99, and it feels like adding i, the last element to be added. Hmm, what? Then why did you write the last element to be added and the counter separately? You'll see that later.

if (postfix)

Now let's make a list with only even numbers. (There is no range (0,99,2))

No2(Not included).py


even=list()
for i in range(100):
    if i%2==0:
        even.append(i)

The result is a long, mediocre code that is easy to read. But this is boring. If you use the inclusion notation

No2(Comprehension notation).py


even=[i for i in range(100) if i%2==0]
#[0, 2, 4, 6,...96,98]

Then, a cool code was created. (Difficult to read? I don't know) However, this makes it difficult for first-time users to understand what the numbers are (I'm not saying I don't know). You can see why this code separates the last element to add and the counter. (Please guess why, I don't have that vocabulary)

No2(First look support)


even=[str(i)+'Is even' for i in range(100) if i%2==0]
#>>['0 is even', '2 is even', '4 is even',...'98 is an even number']

It became easier to understand even at first glance.

The one that includes if and else (conditional operator)

See this for the conditional operator. For example, a program that refers to even or odd numbers

No3(Not included).py


number=[]
for i in range(100):
    if i%2==0:
        number.append(str(i)+'Is even')
    else:
        number.append(str(i)+'Is odd')

Will be. Who wants to read such a long code? In the inclusion notation

No3(Comprehension notation).py


number=[str(i)+'Is even' if i%2==0 else str(i)+'Is odd' for i in range(100) ]

It became a very short code. Hmm? I don't know if you show me this? I'll explain it.

No3(Indent).py


number=[str(i)+'Is even' if i%2==0 else str(i)+'Is odd' for i in range(100)]
#If it is not the result of the previous if statement, enter it

vocabulary()

Postscript Comment from @konandoiruasa What a str (i) + untara kantara part was omitted more.

number=[str(i)+('Is odd' if i%2 else 'Is even') for i in range(100) ]#Is slightly shorter
number=[str(i)+['Is odd', 'Is even'][i%2==0] for i in range(100) ]#Is about the same.

That is. It's certainly a convincing code. I knew my lack of knowledge.

Extreme

Up to this point, everything was simple, but from here on, Python's rule to "write the code so that it is easy to read" is that. All are expressed in inclusion notation. fizzbuzz

fizzbuzz.py


fizzbuzz=[]
for i in range(1,100):
    if i%15==0:
        fizzbuzz.append('fizzbuzz')
    elif i%3==0:
        fizzbuzz.append('fizz')
    elif i%5==0:
        fizzbuzz.append('buzz')
    else:
        fizzbuzz.append(i)

Comprehension notation

fizzbuzz2.py


fizzbuzz=['fizzbuzz' if i%15==0 else 'fizz' if i%3==0 else 'buzz' if i%5==0 else i for i in range(1,100)]
#[1, 2, 'fizz', 4, 'buzz', 'fizz',...'fizz', 97, 98, 'fizz']

Two-dimensional array

Two-dimensional array.py


e=[]
e_=[]
for n in range(3):
    e_=[]
    for i in range(10):
        e_.append(i)
    e.append(e_)

Comprehension notation

Two-dimensional array 2.py


e=[[i for i in range(4)] for n in range(3)]
#[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

Feeling to add a list of tips By the way, 5 dimensions

Five-dimensional array.py


_f=[[[[[z for z in range(3)] for y in range(4)] for x in range(5)] for i in range(4)] for n in range(2)]
#[[[[[0, 1, 2], [0, 1, 2],......[0, 1, 2], [0, 1, 2]]]]]

Double loop

g1=[[0,1,2],[3,4],[5,6,7]]
g=[]
for g2 in g1:
    for g3 in g2:
        g.append(g3)
g1=[[0,1,2],[3,4],[5,6,7]]
_g=[g3 for g2 in g1 for g3 in g2]
#[0, 1, 2, 3, 4, 5, 6, 7]

application

A program that displays the total amount of money including consumption tax

print(['The total is'+str(int(sum([int(input('Product{}Amount of money:'.format((i+1)))) for i in range(int(input('購入するProductの個数を入力し、金額を消費税抜きで入力していってください。購入するProduct数:')))])*1.1))+'It is a circle.(Consumption tax included)'])
Please enter the number of items to purchase and enter the amount excluding consumption tax. Number of products to purchase:4
Amount of product 1:200
Amount of product 2:100
Amount of product 3:140000
Amount of product 4:65520
['The total is 226402 yen.(Consumption tax included)']

Explanation is omitted

Recommended Posts

Python comprehension
About python comprehension
Python> Comprehension / Comprehension> List comprehension
Python Exercise 2 --List Comprehension
Python
Python list comprehension speed
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
List comprehension
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Set comprehension
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
List comprehension
Python update (2.6-> 2.7)
python memo
Python memorandum
Python # sort
ufo-> python
Python nslookup
python learning