學(xué)習(xí)了Python的數(shù)據(jù)類型和變量
字符串的編碼
常用數(shù)據(jù)結(jié)構(gòu):list/tuple dict/set
條件判斷和循環(huán)
** foreach **
names = ['chen', 'li', 'jiang']
# foreach
for name in names:
print name
# for x in ...
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7]:
sum = sum + x
print sum
# range
print range(5)
sum = 0
for x in range(8):
sum = sum + x
print sum
# while loop
sum = 0
n = 8
while n > 0:
sum = sum + 2
n = n - 2
print sum
# raw_input()--字符串
# int()--數(shù)字
** if **
a = 100
if a < 10:
print 'aaa'
elif a < 20:
print 'bbb'
else:
print 'ccc'
if a:
print a
** dict **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
name_score = {'chen': 97, 'li': 0, 'jiang': 90}
# 打印元素
print name_score['chen']
# 元素重新賦值
name_score['chen'] = 34
print name_score['chen']
# 判斷元素是否存在
print 'wen' in name_score
# 指定返回值
print name_score.get('wen', 55)
** list **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 可變數(shù)組
a = ['c', 'a', 'b']
# 訪問元素
print a[0]
print a[-1]
# 長度
print len(a)
# 追加元素
a.append('d')
print a
# 指定位置追加元素
a.insert(0, 'e')
print a
# 刪除元素
a.pop()
print a
# 根據(jù)索引刪除元素
print a.pop(1)
# 替換值
a[0] = 'i'
print a
# 排序
a.sort()
print a
# list 嵌套 list
nerd_list = ['a', 'b', [1, 2], 3]
print nerd_list[2]
print nerd_list[2][0]
print nerd_list
** set **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
nums = set([1, 2, 3, 1])
print nums
# add key
nums.add(5)
nums.add(5)
print nums
# remove key
nums.remove(1)
print nums
nums1 = set([6, 1])
# 求交集
print nums & nums1
# 求并集
print nums | nums1
** tuple **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# tuple為不可變的數(shù)組
classmates = ('chen', 'li', 'jiang')
print classmates
# empty tuple
t = ()
print t
# one element tuple
t = (1,)
print t
# 錯誤的單元素tuple
t = (1)
print t
# 可變的tuple
t = ('a', 'b', ['A', 'B'])
print t[2][0]
t[2][0] = 'C'
print t