li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] #arr是被分割的list,n是每個chunk中含n元素。 def chunks(arr, n): return [arr[i:i+n] for i in range(0, len(arr), n)] m = chunks(li,4) print m
結果:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18]]
#或者讓一共有m塊,自動分(盡可能平均) #split the arr into N chunks def chunks(arr, m): n = int(math.ceil(len(arr) / float(m))) return [arr[i:i + n] for i in range(0, len(arr), n)] m = chunks(li,4) print m
結果:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18]]
###將列表l 進行x等分
def f(l,x): lenth = (len(l) / x if len(l) % x == 0 else len(l) / x+1) return [l[m:m+lenth] for m in range(0, len(l), lenth)]
對列表中的某一項進行排序問題
li = [{'uid':'--','change_reason':'--','change_cash':'--','change_time':'--','stock_code':'--','trade_amount':'--','trade_price':'--','cost_price':'--','fee':'--','trade_rant':'--'},{'uid':'--','change_reason':'--','change_cash':'--','change_time':'--','stock_code':'--','trade_amount':'--','trade_price':'--','cost_price':'--','fee':'--','trade_rant':'--'},{'uid':'--','change_reason':'--','change_cash':'--','change_time':'--','stock_code':'--','trade_amount':'--','trade_price':'--','cost_price':'--','fee':'--','trade_rant':'--'}]
對system_time這個數據進行排序,(升序/降序)
li = sorted(li, key=lambda x: x['system_time'], reverse=True)
class test(object): def __init__(self): pass t = test() for i in range(1, 11): setattr(t, "a" + str(i), []) print t.__dict__ print t.a1
結果:
{'a10': [], 'a1': [], 'a3': [], 'a2': [], 'a5': [], 'a4': [], 'a7': [], 'a6': [], 'a9': [], 'a8': []}
將嵌套列表轉為字典,有兩種方法
new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
dict(list)
>>>>{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}