python2.7零基礎入門練習

寫這篇博客只是爲了督促自己學習python,堅持每日更新

基操

  • 中文編碼
# -*- coding: UTF-8 -*- 
# coding=utf-8
  • 保留字段
and	not	or	exec	assert	finally	break	for	pass	class from
print	continue	global	raise	def	if	return	del	import	
try	elif	in	while	else	is	with	except	lambda	yield
  • 跨行語句

使用" \"將多行寫在一起,注意“\”前面有個空格,後面沒有,否則會報錯。

weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
weekend = ['saturday', 'sunday']

week = weekdays + \
    weekend
print week

運行結果
在這裏插入圖片描述

數據類型 & 列表操作 & 方括號

m_list = ['test_string', \
          # 字符串
          1, 2.0, 3.14j, \
          # 整數 浮點 複數
          (2.0,), \
          # 元組
          {'a': 1, 'b': 'dict_b'}]
            # 字典
print m_list

# 方括號 冒號 規則:
# [起始位 : 終止位 : 步長]
# 正數表示從前往後數位置
# 負數表示從後往前數位置

# 截取
print "截取:", m_list[1:-1]

# 重置爲空
m_list = []
print "重置:", m_list

# 在列表後添加元素
m_list.append('0_test_string')
m_list.append(1.0j)
m_list.append((2.0,))
m_list.append(3)
print "添加:", m_list

# 刪除
del m_list[2]
print "刪除:", m_list
m_list.pop(-1)
print "刪除:", m_list
# 移除最後一個元素 pop()函數支持寫入index
tmp_var = m_list.pop(-1)
print "刪除的元素:", tmp_var, "剩餘的列表", m_list


# 組合
m_list_0 = [4, '5', 6.6]
print "組合:", m_list + m_list_0

# 重複
print "重複3次:", m_list * 3

# 比較兩個列表的長度 似乎cmp函數已經不被python3支持
print "比較長度:", cmp(m_list, m_list_0)
print "比較長度:", cmp(m_list, m_list)
print "比較長度:", cmp(m_list_0, m_list)

# 反向
m_list.reverse()
print "反向:", m_list

# 插入
m_list.insert(1, 0.5)
print "插入:", m_list

操作結果如下…
啥玩意 啊z'zzz

字典 & 簡單循環

字典類型有點像map,提供了一種靈活的映射關係。

  • dict是無序的
m_dict = {'a': 1, 'b': 3, 'c': 2, 'd': '11111'}
print m_dict

輸出的順序與存入的順序無關。
在這裏插入圖片描述

  • 創建
m_dict = {'a': 1, 'b': 3, 'c': 2}
print "m_dict: ", m_dict

m_dict_create = {}
print "m_dict_create: ", m_dict_create
m_dict_create['a'] = 'Alice'
m_dict_create['b'] = 2
m_dict_create[3] = 3
print "m_dict_create: ", m_dict_create

在這裏插入圖片描述

  • 按鍵值排序
for key in sorted(m_dict):
    print key, "->", m_dict[key]

在這裏插入圖片描述

  • 用key來取值
    實際上這個問題關鍵在於,如果這個字典裏面不存在這個key,要怎麼處理。使用get就好啦。
val_get_s = m_dict.get('s')
val_get_a = m_dict.get('a')
print "鍵值爲‘s’:", val_get_s
print "鍵值爲‘a’:", val_get_a

在這裏插入圖片描述

不怕麻煩的話,可以寫一下if語句來查看鍵值是否在字典裏面。

if 'a' in m_dict:
    print '\'a\'在字典中,值爲: ', m_dict['a']
else:
    print "\'a\'不在字典中"

if 's' in m_dict:
    print "\'s\'在字典中,值爲:", m_dict['s']
else:
    print "\'s\'不在字典中"

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章