LoginSignup
2
2

More than 5 years have passed since last update.

pythonメモ

Posted at
Test.py

# テスト用の多次元リストを生成
xss = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print xss

# まずは通常のループで出力
yss = []
for xs in xss:
    ys = []
    for x in xs:
        ys.append(x * 2)
    yss.append(ys)
print yss

# リスト内包表記で出力
print [[x * 2 for x in xs] for xs in xss]

# フラット出力(1次元配列に変更)
print [x * 2 for xs in xss for x in xs]

# set出力
print {x / 2 for xs in xss for x in xs}

# 辞書出力
print {x:str(x * 2) for xs in xss for x in xs}

# ジェネレート出力
it = (x * 2 for xs in xss for x in xs)
print it.next()
print it.next()

def gen():
    for xs in xss:
        for x in xs:
            yield x * 2
it = gen()
print it.next()
print it.next()

# ソートテスト
print sorted(gen())
print sorted([[x * 2 for x in xs] for xs in xss], reverse=True)
print [1, 2] == [1, 2]
print [1, 2] < [1, 2, 3]
print [1, 2, -1, 3, 4] > [1, 2, 3]

# 可変長引数
# *がリスト
# **が辞書
def f(*args, **kwargs):
    print args
    print kwargs

f(1, 2, 3, a=10, b=20, c=30)

# いろいろな引数の引き渡しテスト
def g(a, b, c):
    print a, b, c

g(10, b=20, c=30)

x = [1, 2, 3]

# 通常の渡し方
g(x[0], x[1], x[2])

# リストとしての渡し方
g(*x)


y = {'a': 10, 'b': 20, 'c': 30}
# 通常の渡し方
g(a=y['a'], b=y['b'], c=y['c'])

# 辞書としての渡し方
g(**y)
x = [1]
y = {'b': 20, 'c': 30}
g(*x, **y)

# formatテスト
print '{hoge} {fuga}'.format(hoge=10, fuga=20)
print '{0} {1}'.format(*(value for value in range(0, 2)))

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2