Skip to content

Instantly share code, notes, and snippets.

@kkas
Last active February 25, 2016 04:18
Show Gist options
  • Save kkas/86c40197917368e395e6 to your computer and use it in GitHub Desktop.
Save kkas/86c40197917368e395e6 to your computer and use it in GitHub Desktop.
Python Tips for myself

Python

Syntax and Grammer

Data Types

string

word = 'soccer'
for c in word:
    print c

# OUTPUT
s
o
c
c
e
r
  • trailing comma will keep the same line
phrase = "A bird in the hand..."

for char in phrase:
    if char == 'A' or char == 'a':
        print 'X',
    else:
        print char,

print

# OUTPUT
X   b i r d   i n   t h e   h X n d . . .
  • reverse
str = "abcd"
abcd[::-1]

#OUTPUT
'dcba'

list

  • Use enumerate() for its index with using for...in loop
list = ['udon', 'ramen', 'spaghetti']
for index, item in enumerate(list):
    print index, ' ', item

# OUTPUT
0   udon
1   ramen
2   spaghetti
  • Use zip() for multiple lists
list = ['udon', 'ramen', 'spaghetti']
list2 = ['breakfast', 'lunch', 'dinner']
list3 = ['hungry', 'full', 'possible']

for a, b, c in zip(list, list2, list3):
    print a, b, c

# OUTPUT
udon breakfast hungry
ramen lunch full
spaghetti dinner possible

### CAUTION! ###
list4 = ['less_item']
for a, b, c, d in zip(list, list2, list3, list4):
    print a, b, c, d

# OUTPUT
udon breakfast hungry less_item # ONLY 1 iteration
  • list.sort() and sorted() will sort the element in a list, according to the code point of the element in question
# list.sort() changes itself
lst = [2, 3, 1, 4]
lst.sort()
print lst

# OUTPUT
[1, 2, 3, 4]


lst2 = [2, 3, 1, 4]
new_lst = sorted(lst2)
print new_lst
print lst2

# OUTPUT
[1, 2, 3, 4]
[2, 3, 1, 4]

## About code point
ord('a') # 97
ord('b') # 98

dictionary

  • for...in loop will iterate it with each key
dict = {'a': 'John', 'b': 'Tom'}
for key in dict:
    print key, ' ', dict[key]

# OUTPUT
a   John
b   Tom

Sequence Types

letters = ['a', 'b', 'c', 'd']
print " ".join(letters) # a b c d
print "---".join(letters) # a---b---c---d
  • tuples
# tuple can be a key in an dictionary
dic = {('this', 'is', 'tuple'): True}
dic[('this', 'is', 'tuple')]

# OUTPUT
True
  • bytearrays
  • buffers
  • xrange objects

Comprehension (内包表記)

  • List (リスト)
# Basic syntax
[x for x in ['1', '2', '3']]

# Basic comprehension + if statement.

# Find elements in interger_list that are not in values_list
[x for x in integer_list if x not in values_list]

# Equivalent
new_list = []
for x in integer_list:
  if x not in values_list:
    new_list.append(x)
  • Sets
  • Tuples
  • Vectors

Syntax

# Workaround
def my_function(str):
    switch = {
        'a': "This is A",
        'b': "This is B", 
        'c': "This is C",
    }
    return switch.get(str, "This is default")
  • There IS a ternary operation (kind of?)
def is_even(x):
    return True if x % 2 == 0 else False

is_even(3)
is_even(6)

# OUTPUT
False
True
  • while...else statement
count = 0
while count < 3:
    print "count: ", count
    count += 1
else:
    print "count is 3"

# OUTPUT
count:  0
count:  1
count:  2
count is 3
  • for...else statement works just like while...else
for i in range(5):
    print i
else:
    print "This is the end of the for loop."

# OUTPUT
0
1
2
3
4
This is the end of the for loop.
  • except that the loop ends normally. This is true for both while...else and for...else loop.
fruits = ['banana', 'tomato', 'apple', 'orange']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'

# OUTPUT
A banana
A tomato is not a fruit! # the print statement in else: is not printed.
  • binary number in 0bxxx format. bin(n) to convert int to the binary representation.
print 0b0 # 0
print 0b1 # 1
print 0b10 # 2

print bin(10) #0b1010

print int("11001001", 2) # 201 in base10

Import

引数

def test(**settings):
   print('settings: {}'.format(settings))


test(aaa)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes 0 positional arguments but 1 was given

test(**aaa)

settings: {'hoge': 'hoge', 'fuga': 'fuga'}

def test2(setting):
   print('setting: {}, {}'.format(type(setting), setting))

test2(aaa)

setting: <class 'dict'>, {'hoge': 'hoge', 'fuga': 'fuga'}

Tips

# This prints '000123'
print "{0:0>6}".format(123)

# This prints '123'
print "{0:0>3}".format(123)
  • Find a number that is an interger. Note that 7.0 should be considered as an interger.
def is_int(x):
    return True if x % 1 == 0 else False

is_int(1)
is_int(-1)
is_int(3.0)
is_int(3.3)
is_int(-4.0)
is_int(-4.2)

# OUTPUT
True
True
True
False
True
False
  • Sort a tuple. If it is a list of tuples, sorted() will check the 0th item in each tuple using the code point.
my_tuple = ('ask', 'push', 'pull', 'del')
print sorted(my_tuple)

# OUTPUT
['ask', 'del', 'pull', 'push']


# a list of tuples
lst = [('zedd', 'is', 'awsome'), ('ask', 'push', 'pull', 'del'), ('be', 'ambitious')]
print sorted(lst)

# OUTPUT
[('ask', 'push', 'pull', 'del'), ('be', 'ambitious'), ('zedd', 'is', 'awsome')]

Style Guides

LIGHT_MESSAGES = {
    'English': "There are %(number_of_lights)s lights.",
    'Pirate':  "Arr! Thar be %(number_of_lights)s lights."
}

def lights_message(language, number_of_lights):
    """Return a language-appropriate string reporting the light count."""
    return LIGHT_MESSAGES[language] % locals()

def is_pirate(message):
    """Return True if the given message sounds piratical."""
    return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None

文字コード

考え方整理メモ

  • 前提

    • Unicodeは文字コードではない
    • utf-8とは文字コードである
    • Unicodeは文字列である
    • 文字コードとはバイト列と文字の対応関係
  • Python2の場合

    • str型とunicode型が存在する('あ' と u'あ' がそれぞれに対応)
    • str型は「文字コード」に則ったバイト列で、入出力に使用される
    • unicode型は「文字コード」にとらわれない形で、CPUやメモリ上で使用される
    • str型は文字コードに則った形なため、則った文字コードでdecodeする
      • 'あ'.decode('utf-8') (unicode型になる)
    • unicode型は文字コードに則らない形なため、則る文字コードでencodeする
      • u'あ'.encode('utf-8') (str型になる)
  • Python3の場合

    • str型はpython2のunicodeと同じであると考えられる
    • バイト型(bytes)がpython2のバイト文字列に似ているが、python2は文字列に対して、python3では文字列ではない
      • サポートされるメソッドが文字列と異なる
      • 文字列と連結が不可
  • 参考:

Python2 tips

pythonのデフォルトエンコーディングをutf-8に変更する
http://qiita.com/puriketu99/items/55e04332881d7b679b00

上記を作成するスクリプト内で都度行う場合は
import sys
# システムモジュールの再読み込み
reload(sys)
# デフォルト文字コードの設定
sys.setdefaultencoding('utf8')

コンソール系スクリプトでエラーが出る場合は

# コンソールの文字コード制御
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
virtualenvの場合、以下の要領で追加できる。(なければ作成すればよい)
参考: http://qiita.com/simota/items/c994629a2124c8c1bc2d

(カレントはvirtualenvで作成したdir.)
touch ./lib/python2.7/site-packages/sitecustomize.py
echo 'import sys' >> ./lib/python2.7/site-packages/sitecustomize.py
echo 'sys.setdefaultencoding("utf-8")' >> ./lib/python2.7/site-packages/sitecustomize.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment