Skip to main content
 首页 » 编程设计

python之反向列表,列表乘以 -1

2025年05月04日15落叶

预期结果:

>>> createLists(5) 
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [ -5, -4, -3, -2, -1], [-1, -2, -3, -4, -5]) 

我的代码:

  # Write a function that returns 4 lists given a postive number. 
    def createLists(num):  
        ls =    [item for item in range(num)] 
        return set(ls, ls.reverse(), ls.reverse()*(-1), ls*(-1)) 

有人指导我怎么做吗?

请您参考如下方法:

def createLists(num):  
    ls = range(1, num+1) 
    return (ls, ls[::-1], [-n for n in ls][::-1], [-n for n in ls]) 
 
print createLists(5) 

http://ideone.com/B0ixx