python 创建多个列表_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'}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值