Python 列表嵌套多种实现方式

本文详细介绍了使用Python进行列表嵌套的多种实现方式,包括传统循环、列表推导及map函数应用,展示了如何将一维列表转换为二维列表,适用于不同场景的数据处理需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 列表嵌套多种实现方式

#coding=utf-8
list=[]
for i in range(1,101):
    list.append(i)

# print(list)

tempList=[]
newList=[]

while True:
    num=0
    for temp in list:
        tempList.append(temp)
        num+=1
        if num==3:
            newList.append(tempList)
            tempList=[]
            num=0
            continue
    if temp==100:
        newList.append(tempList)
        break

print(newList)

复制代码

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24],.......[100]]

 

oldList=[x for x in range(1,101)]
newList=[oldList[x:x+3] for x in range(0,len(oldList),3)]
print(newList)

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24],.......[100]]

 

def f(x,y,z):
    return x,y,z

m = list(map(f, [x for x in range(1,101,3)], [y for y in range(2,101,3)], [z for z in range(3,101,3)]))
print(list(m))

输出:

[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12), (13, 14, 15), (16, 17, 18), (19, 20, 21), (22, 23, 24),......(100)]

类似方法还有很多,需要多多研究

转载请注明出处:http://www.cnblogs.com/sexyboy/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值