Python列表切成多个/生成多个空列表

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'}

原文地址:https://www.cnblogs.com/mosson/p/6092990.html