小编haj*_*muz的帖子

用条件切片列表的优雅方法

给定一个列表[2,8,13,15,24,30],其中所有元素都应该在范围内(31).现在我想把它分成3个列表,第一个列表的数字从0到10,第二个列表的数字从11到20,其他的到其余的.

这是我丑陋的代码:

numbers = [2,8,13,15,24,30]
mylist = [[],[],[]] # I hate this the most...
for i in numbers:
    if i <= 10 :
        mylist[0].append(i)
    elif i > 10 and i <= 20:
        mylist[1].append(i)
    else:
        mylist[2].append(i)

print mylist
Run Code Online (Sandbox Code Playgroud)

我不认为这是一个很好的方法.有什么建议吗?

python list

5
推荐指数
1
解决办法
129
查看次数

标签 统计

list ×1

python ×1