代码之家  ›  专栏  ›  技术社区  ›  user3042850

写一个列表,然后将其反向返回[关闭]

  •  -1
  • user3042850  · 技术社区  · 6 年前

    写一个5个数字的列表,然后再写一个数值颠倒的列表…

    解决方案1有效。解决方案2,没那么多。

    counter = 0
    count2 = 0
    list = []
    otherlist = []
    
    import random
    
    #Solution 1
    list = random.sample(range(1, 100), 5)
    otherlist = list.reverse    
    
    #Solution 2
    while counter<5:
        list.append(random.randint(5,10))
        print(list[counter])
        counter = counter + 1
    
    counter = counter - 1
    
    while counter > (-1):
        templist.append(list[counter])
        print(list[counter])
        print("Real",templist[count2])
        counter = counter - 1
        count2 = count2 + 1
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Waket Zheng    6 年前

    如果要反转列表,请执行以下操作:

    # Solution 1
    alist = random.sample(range(1, 100), 5)
    otherlist = list(reversed(alist))
    
    # Solution 2 (My favourite)
    otherlist = alist[::-1]
    
    # Solution 3
    otherlist = alist[:]
    otherlist.reverse()
    
    # Solution 4
    otherlist = []
    for i in range(len(alist)-1, -1, -1):
        otherlist.append(alist[i])
    
    # Solution 5
    counter = count2 = 0
    alist, templist = [], []
    while counter<5:
        alist.append(random.randint(5,10))
        print(alist[counter])
        counter += 1
    
    while counter > 0:
        counter -= 1
        templist.append(alist[counter])
        print(alist[counter])
        print("Real",templist[count2])    
        count2 += 1