python 三角形阵列_将一维阵列转换为下三角矩阵

您也可以尝试下面的函数来获取列表。在import pprint

def get_triangled_list(l, rows, typ='lower'):

if type(l) is not list:

print 'First parameter should be a list'

return None

if type(rows) is not int:

print 'Second parameter should be a list'

return None

if not(typ == 'lower' or typ == 'upper'):

print 'ERROR:', typ, 'is not allowed type'

return None

new_l = []

length = len(l)

num_items = ((rows-1) * rows)/ 2

if length != num_items:

print 'ERROR: ', 'There should be exactly', num_items, 'items for ', rows, 'rows, found', length, 'items.'

return None

if typ == 'upper':

for i in range(rows):

temp_l = [0]*(i+1) + [l.pop(0) for j in range(7-(i+1))]

new_l.append(temp_l)

elif typ=='lower':

for i in range(rows):

temp_l = [l.pop(0) for j in range(i)] + [0]*(rows-i)

new_l.append(temp_l)

return new_l

if __name__ == '__main__':

l = [10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12]

# TEST CASE 1 (LOWER TRIANGLE, default)

new_lower = get_triangled_list(l, 7)

pprint.pprint(new_lower)

print('\n')

# TEST CASE 2 (UPPER TRIANGLE, passing one more parameter)

l = [10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12]

new_upper = get_triangled_list(l, 7, 'upper')

pprint.pprint(new_upper)

输出»

^{pr2}$

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值