Python菜鳥文法小技巧

1820 ワード

いくつかのpython構文のテクニックを記録します.
1.変換変数
x = 5
y = 6
x, y = y, x
print  x,y

2.行内if文
print 'Python' if True else 'Objective-C'

3.接続
l1 = ['python','objective-c']
l2 = ['swift']
l3 = l1 + l2
print l3

4.下揃え
print 5.0//2
print 2**5

5.浮動小数点数の除算
print .3/.1
print .3//.1

6.数値比較
x = 2
if 3 > x < 1:
    print x
if 1 < x > 0:
    print x

7.2つのリストの同時反復
l1 = ['python','objective-c']
l2 = ['swift','javascript']
#zip            ,                tuple
for item1,item2 in zip(l1,l2):
    print item1,item2

8.インデックス付き反復
l1 = ['python','objective-c','swift','javascript']
for index,language in enumerate(l1):
print language + ' index is ' + str(index)

9.リスト導出
nums = [x for x in range(11)]
    print nums
nums2 = [x for x in nums if x%2 == 0]
    print nums2

10.インデックスの導出
dict = {'name':'shuige','age':'20'}
    print {key:value for value,key in enumerate(dict)}

11.初期化リスト
items = [0]*3
    print items

12.リストを文字列に変換
l1 = ['python','objective-c','swift','javascript']
    print ','.join(l1)

13.辞書の要素
dict = {'name':'shuige','age':'20'}
#    ,  ,    ,   True
name = dict.get('name',True)
    print name

14.スライス
x = [x for x in range(11)]
print x[:3]
print x[1::2] #   1      
print x[1::3]