Python beginner memo (2)

I played with Python more and learned a little more, so I will write it as a continuation of Last time.

It doesn't matter, but the Python user is called Pythonista. Aim Pythonista! !!

Array system

Element access

Usual

items = ["A", "B", "C", "D", "E"]
item = items[1] #Get the element of index 1
print(item) # B

Recently learned

items = ["A", "B", "C", "D", "E"]
item = items[-1] #Get the last element
# item = items[len(items) - 1] #You don't have to do this
print(item) # E

If you specify -2, you can get the second "D" from the back.

Array copy

I wrote last time, but it looks like this.

items = ["A", "B", "C", "D", "E"]
items2 = items[1:3] #List generation that extracts index 1 to 2
print(items2) # ['B', 'C']

items3 = items[1:] #List generation that extracts everything after index 1
print(items3) # ['B', 'C', 'D', 'E']

items4 = items[:3] #List generation that extracts everything before index 3
print(items4) # ['A', 'B', 'C']

In addition, it can be taken in a discrete manner.

items = ["A", "B", "C", "D", "E", "F", "G"]
items6 = items[::2] #List generation extracted by skipping one
print(items6) # ['A', 'C', 'E', 'G']

items7 = items[::-1] #Reverse list generation
print(items7) # ['G', 'F', 'E', 'D', 'C', 'B', 'A']

items8 = items[-1:3:-1] #If you specify the index range in reverse order, start at the back. (If you reverse it, you cannot remove the element)
print(items8) # ['G', 'F', 'E']

for statement

Of course, you can use [::] to create various array loops.

items = ["A", "B", "C", "D", "E", "F", "G"]
for item in items[1:]:
    print(item) # B,C,D,E,F,Print G in order

print("---")

for item in items[::-1]:
    print(item) # G,F,E,D,C,B,Print A in order

print("---")

for item in items[::3]:
    print(item) # A,D,Print G in order

Take index with for statement

There was a way.

items = ["A", "B", "C", "D", "E"]

for i, value in enumerate(items):
    print(str(i) + ":"+ value)

result

0:A
1:B
2:C
3:D
4:E

List comprehension

(Maybe it's different from the for statement) http://docs.python.jp/3.5/tutorial/datastructures.html#list-comprehensions

When you want to manipulate the contents of an array to create another array

items = ["a", "B", "c", "D", "e"]

#Make a capitalized list
items2 = []
for item in items:
    items2.append(item.upper())

print(items2) # ['A', 'B', 'C', 'D', 'E']

Where it seems to be written, the processing of the loop that creates items2 can be written as follows.

items2 = [item.upper() for item in items]

By the way, if you use map, you can write as follows.

items2 = list(map(str.upper, items))

further,

items = ["a", "B", "c", "D", "e"]

#Make a list with only uppercase letters
items2 = []
for item in items:
    if item.upper() == item:
        items2.append(item)

print(items2) # ['B', 'D']

Where it seems to be written, the processing of the loop that creates items2 can be written as follows.

items2 = [item for item in items if item.upper() == item]

Join

Python array binding that is quite impressive personally It was made only with the + operator.

item1 = ["A", "B", "C"]
item2 = ["D", "E"]

item3 = item1 + item2
print(item3) # ['A', 'B', 'C', 'D', 'E']

(Unlike extend, another list is created)

As you can expect, of course, addition substitution is also possible

item1 = ["A", "B", "C"]
item2 = ["D", "E"]

item1 += item2
# item1.extend(item2)And the result is the same
print(item1) # ['A', 'B', 'C', 'D', 'E']

And I personally don't understand at all.

item1 = ["A", "B", "C"]
item2 = ["D", "E"]

item1[:0] = item2
print(item1) # ['D', 'E', 'A', 'B', 'C']

If you write as above, you can combine it with your head.

I'm not used to it, so I can't understand it, so for the time being

item1 = item2 + item1

I think I will write.

String manipulation

join (Last time Maybe it should have been written)

s = ":".join(["A", "B", "C", "D", "E"])

print(s) # "A:B:C:D:E"

repetition

This is also a method that I am quite impressed with. It was made only with the * operator. (I wrote a loop until I knew this)

s = "Ah" * 5
print(s) #Ahhhh

lambda expression

Write like this. The way to write a lambda expression is not much different from Java now.

func = lambda x: x.upper()

print(func("a")) # A

Conditional statement

in Determine (or) whether it is included in the array. (The operation is different with dict) A convenient one that doesn't have to be connected with or.

http://docs.python.jp/3.5/reference/expressions.html#membership-test-operations It seems that the name is attribution inspection operation. Like SQL IN? A personal memory that I could have done with Temple Mark Language.

if 2 in [1, 2, 3]: # True
    print("There are 2")

if 4 not in [1, 2, 3]: # True
    print("4 is not")

yield

http://docs.python.jp/3.5/reference/expressions.html#yieldexpr http://docs.python.jp/3.5/reference/simple_stmts.html#the-yield-statement

I can't explain what the yield is, so refer to the following https://ja.wikipedia.org/wiki/ジェネレータ_(プログラミング)

I understood how to easily create Iterator in Java.

def yield_sample():
    for i in [1, 2, 3]:
        yield i

gen = yield_sample()

print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3
print(next(gen))  # StopIteration
for i in yield_sample(): #Can be turned with a for statement
    print(i)  #Output 1, 2 and 3 in order

Next is the interesting part of yield

def yield_sample2():
    print("Next is 1")
    yield 1
    print("Next is 2")
    yield 2
    print("Next is 3")
    yield 3
    print("There is no next")

for i in yield_sample2():
    print(i)  #Outputs 1, 2 and 3 in order, but ...

The result is

Next is 1
1
Next is 2
2
Next is 3
3
There is no next

If you want to list the generator created by yield,

def yield_sample():
    for i in [1, 2, 3]:
        yield i

l = list(yield_sample())
print(l) # [1, 2, 3]

File operation system

It may be faster to google. I got the impression that there are several ways to do it. I don't know which method is the best. I won't write all the file operations, but I will write only the ones I used.

Read

f = codecs.open(path, "r", "utf-8")
ret = f.read()
f.close()

writing

f = codecs.open(path,"w", "utf-8")
f.write(value)
f.close()

File exists

if os.path.exists(path):

Digging a folder

os.makedirs(dirPath)

Get parent folder name

os.path.dirname(path)

List files from directory

for root, _, files in os.walk(dirPath):
    for fileName in files:
        path = os.path.join(root, fileName)
        yield path

Exception handling

except Catch block in Java

def error_throw():
    "" + 1

try:
    error_throw()
    print("Don't come here")
except: #Come here with all errors
    print("error")

catch-like guy

try:
    error_throw()
    print("Don't come here")
except Exception as e: #Get error Object
    print(type(e))
    print(e)

result

<class 'TypeError'>
Can't convert 'int' object to str implicitly

Also apply to Exception type

try:
    error_throw()
    print("Don't come here")
except ValueError:
    print("ValueError does not occur, so it does not come here")
except TypeError:
    print("I'm here because I get a TypeError")

trace Stacktrace nice guy in Java

import traceback

try:
    error_throw()
except :
    print(traceback.format_exc())

closure

Can not. I'm sorry. You can't do it with an image similar to Java.

def new_counter():
    count = 0
    def func():
        count += 1
        return count
    return func

c = new_counter()
print(c())
print(c())
print(c())

error

UnboundLocalError: local variable 'count' referenced before assignment

You can do something like that by writing as follows. .. .. (Like Java)

def new_counter():
    count = [0]
    def func():
        count[0] += 1
        return count[0]
    return func

c = new_counter()
print(c())
print(c())
print(c())

test

Create

From Eclipse "New"-> "Pydev Module"-> Name and "Done"-> If you select "Module: Unittest" and see what you can do with "OK", you can understand how to write it.

Run

It can be executed by "Run"-> "Python unit test".

sample

import unittest


class Test(unittest.TestCase):


    def testName(self):
        self.assertEqual(1, 2, "sample")


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

result

F
======================================================================
FAIL: testName (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\hogehoge\testsample.py", line 13, in testName
    self.assertEqual(1, 2, "sample")
AssertionError: 1 != 2 :sample

----------------------------------------------------------------------
Ran 1 test in 0.016s

FAILED (failures=1)

Dynamic addition of tests

I referred to the following. http://hirokazumiyaji.hatenablog.com/entry/2015/07/16/134238

The sample below is a sample to register the test for the files in the directory.

import unittest
import os


class Test(unittest.TestCase):
    #Empty test class
    pass

def setup_testsuite():
    """
Register the test by listing the files in the directory
    """
    root = os.getcwd()
    test_files_dir = os.path.join(root, "files") #Target files in the files folder next to this py file

    def listup():
        for root, _, files in os.walk(test_files_dir):
            for file_name in files:
                if os.path.splitext(file_name)[1].lower() == ".txt":#Narrow down by extension
                    yield file_name, os.path.join(root, file_name)

    for file_name, path in listup():
        def create_test_func(file_name, path):
            def test_func(self):
                """
Actual condition of the test
                """
                print("test start: " + file_name)

                #Since self is Test, assertEqual is called as follows
                # self.assertEqual(first, second, msg)

            return test_func

        test_name = "test_{}".format(file_name)
        setattr(Test, test_name, create_test_func(file_name, path)) #Registration

#Perform test registration
setup_testsuite()

if __name__ == "__main__":
    # import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

Recommended Posts

python beginner memo (9.1)
Python beginner memo (2)
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
Beginner ABC154 (Python)
[Python] Memo dictionary
Beginner ABC156 (Python)
Python beginner notes
★ Memo ★ Python Iroha
Beginner ABC155 (Python)
[Python] EDA memo
Python 3 operator memo
[Beginner] Python functions
Beginner ABC157 (Python)
PyQ ~ Python Beginner ~
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner Zundokokiyoshi
[Python] Numpy memo
[Python beginner memo] Python character string, path operation
Python class (Python learning memo ⑦)
My python environment memo
python openCV installation (memo)
Python module (Python learning memo ④)
Visualization memo by Python
Python test package memo
python regular expression memo
Binary search (python2.7) memo
[My memo] python -v / python -V
Python3 List / dictionary memo
Python Tips (my memo)
[Python] Memo about errors
DynamoDB Script Memo (Python)
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
Python basic grammar memo
TensorFlow API memo (Python)
python useful memo links
Python decorator operation memo
Python basic memo --Part 1
Effective Python Memo Item 3
Divisor enumeration Python memo
A memo for creating a python environment by a beginner
Python memo (for myself): Array
Python exception handling (Python learning memo ⑥)
Python execution time measurement memo
python super beginner tries scraping
Python
Twitter graphing memo with Python
[Line / Python] Beacon implementation memo
Python and ruby slice memo
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Raspberry Pi + Python + OpenGL memo