Archive for python

[python] 將 dictionary 排序並由大往下排

image

 

定義以下 function

#排序 dictionary
def sortedDict(d):
    items=d.items()
    backitems=[ [v[1],v[0]] for v in items]
    backitems.sort()
    return [ backitems[i][1] for i in range(0,len(backitems))]

會回傳一個 list 型態,根據值去 sort 並回傳 key 的順序

範例如下:

test={}
test['num1']=10
test['num2']=66
test['num3']=34
test['num4']=21
test['num5']=77
test['num6']=12

t = sortedDict(test)
        for h in t:
            print h  #依照排序後的順位印出來 (由小而大)

 

印出的結果為

num1
num6
num4
num3
num2
num5

 

如果要改由大而小排序

因為回傳的型態是 list ,可以使用 reverse() fn 來改變順序

t.reverse()
        for h in t:
            print h

印出的結果為

num5
num2
num3
num4
num6
num1

[python] List (串列) 與 dictionary (字典) 基本指令

image

在 python 中沒有陣列,一般都是用 dictionary 這種東西來取代之
每次都很容易搞混這兩個東西,這篇文章把它們兩個的指令好好整理一下

List 部份(順序固定)


# 起始化 list
L1= {‘I’:1,’II’:2,’III’:3,’IV’:4,’V’:5,’VI’:6,’VII’:7,’VIII’:8,’IX’:9}

# value list 值可以排序,但字典不行
L1.sort()

#插入一個值
L1.append(‘value’)

#在指定位置插不一個值
L1.insert (index,’value’)

#移除一個值
L:1.remove(‘value’)

Dictionary 部份(順序不固定)
# 建立一個空白的字典
D1 = {}

# 顯示字典
print D1


# 顯示字典長度
print "Length = ", len(D1)


# 增加新的 key 與其相對應的 value
D1['0'] = ‘zero’
D1['1'] = ‘one’
D1['2'] = ‘two’
D1['3'] = ‘three’
D1['4'] = ‘four’


# 從 key 找到其相對應的 value
print "The english word for drei is ", D1['1']


# 更直覺的方式從 key 找到 value
if 1in D1:
    print "The english word for drei is ", D1[1]


# key list 值可以排序,但字典不行
L2 = D1.keys()
L2.sort()


# copy 一個字典 (但順序不一定相同)
D2 = D1.copy()


# 刪除一筆紀錄
del D2['1']


# 取出某個值的同時刪除這筆紀錄
e3 = D2.pop(‘drei’)


#存取字典與檔案
import pickle
print romanD
file = open("roman1.dat", "w")
pickle.dump(romanD1, file)
file.close()
file = open("roman1.dat", "r")
romanD2 = pickle.load(file)
file.close()
print "Dictionary after pickle.dump() and pickle.load():"
print romanD2

List 與 Dictionary 互相轉換部份


#插入一個  list 的值進入 dictionary, index 名稱自行指定
L1={ }
Li = [1,2,3,4,5]
L1[index] = Li


# 取出 Ditionary 裡的值,是一個 list
L1 = D1.values()


# 將 dictionary 切割成兩個 list
romanD = {‘I’:1,’II’:2,’III’:3,’IV’:4,’V’:5,’VI’:6,’VII’:7,’VIII’:8,’IX’:9}
romankeyList = []
romanvalueList = []
for key, value in romanD.items():
    romankeyList.append(key)
    romanvalueList.append(value)


# 從兩個list 合併成為一個 dictionary
romanD1 = dict(zip(romankeyList, romanvalueList))

相關閱讀
python tutorial – list
xperimenting with Dictionaries (Python)
Python List, Python Tuple, Python Dictionary

[python] 清除 string 雜物

一般文章都會有很多雜物浪費空間,所以以下指令可以有效清楚三種雜物

 

(1) 清除換行 (space)

StringReplace = lambda x: “.join(x.split(‘\n’))
content=StringReplace(value)

 

(1) 清除空格 (enter)

StringReplace = lambda x: “.join(x.split(‘ ‘))
content2=StringReplace(content)

 

(3) 清楚跳格 (tab)

StringReplace = lambda x: “.join(x.split(‘\t’))
content3=StringReplace(content2)

[python] 解讀 json

image

 

寫論文有用到,來筆記一下

首先到 這裡 安裝 library

再來到 這裡 看 document

 

在程式剛開始要先 import module

import simplejson as json

接下來用一些基本指令來了解

 
 
丟入 a b c 三個 key index ,值分別是 0 0 0 ,然後 keys 要 sort 
 
print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)

結果為  {“a": 0, “b": 0, “c": 0}

 

將 json 結果的值丟入變數並以漂亮的方式印出來

s = json.dumps({’4′: 5, ’6′: 7}, sort_keys=True, indent=4 * ‘ ‘)

結果為

{
"4": 5,
"6": 7
}

 

 

傳入字串值進 JSON 當中

from StringIO import StringIO
io = StringIO(‘["streaming API"]‘)
json.load(io)[0]

 

將取回來的中文轉碼並印出來

url=’http://funp.com/push/api/api.php?op=getPostFulltext&post_id=1226646′

json_str = urllib.urlopen(url)
    j = json.load(json_str)
    for key, value in j.items():
        print ‘key=’+key
        try:
            type = sys.getfilesystemencoding()
            print ‘value=’+unicode(value).encode(type)
        except:
            print ‘error’

[UltraEdit] 使用技巧

image

在讀 http://www.dbanotes.net/techmemo/ultraedit.html 這篇文章

最近都在用 UltraEdit 寫論文的程式,順便筆記一下讓效率增加的方法

有一些是自己無意中按到的

 

(1) 快速取代相關字串

使用 Ctrl + R (取代) 加上 *字串* 即可

(2) 尋找空白的行

使用 Ctrl + F (尋找) 加上 ^p$

(3) 加入時間戳記

Ctrl + F7

(4) 切換 windows 剪貼與 UltraEdit 內建剪貼

按 Ctrl + 0 換 Windows的,其他 Ctrl 1 ~ 9 是內建

(5) 刪除一行

Ctrl e

(6) 切換凱啟中的不同檔案

alt + 上下

(7) 將左邊的檔案顯示區先關掉

ctrl + u

(8)