将列表返回给函数

时间:2016-11-13 00:23:25

标签: function list-comprehension

import random

def genList1():
     list1 = [x for x in range(100)]
     count = 0
     for count in list1:
        print(random.randint(2,25), end = " ")
     return

def main():
    print(genList1())

main()

上述代码 - 在2到25之间正确打印100个随机数字,但对函数返回“无”。如何在以下代码中将100个随机数字列表返回给我们的函数。

import random

def genList1(): 
    list1 = [x for x in range(100)]
    count = 0
    for count in list1:
        random.randint(2,25)
    return list1

def genList2():
    list1 = genList1()
    list2 = [x**2 for x in list1 if x % 2 == 0]
    return list2

def genList3():
    list2 = genList2()
    list3 = [0.5*x for x in list2]
    return list3

def genSum1_2():
    list2 = genList2()
    list3 = genList3()

    sum1 = 0
    number1 = 0
    for number1 in list2:
        sum1 = sum1 + number1

    sum2 = 0
    number2 = 0
    for number2 in list3:
        sum2 = sum2 + number2

    return sum1, sum2

def main():
    print("Here is List 1, which contains 100 random digits between 2 and 25: ")
    print(genList1())
    print(), print()
    print("Here is List 2, which is the cubes of all the even digits in List 1: ")
    print(genList2())
    print(), print()
    print("Here is List 3, which is all the digits in List 2 divided in half: ")
    print(genList3())
    print(), print()
    print("Here is the sum of the digits in List 2, and digits in List 3: ")
    print(genSum1_2())

main()

我尝试了一些不同的改动,例如在打印前添加返回(随机....)以及尝试将打印(随机.....)分配给变量然后返回该变量......无济于事。

1 个答案:

答案 0 :(得分:2)

import random

def getRandList():
    return [random.randint(2,25) for x in xrange(100)]

print getRandList()

或者,如果您希望它的行为更像原始代码......

import random

def genList1():
    randlist = [random.randint(2,25) for x in xrange(100)]
    for elem in randlist:
        print(elem, end = ' ')
    return randlist

def main():
    print(genList1())

main()

编辑(在下面的评论中说明问题):

如果您想重复使用该列表中的随机数,您可以选择一些选项。

选项1:最佳选择

将列表作为参数传递给后续函数。

def genList2(input_list):
    list2 = [x**2 for x in input_list if x % 2 == 0]
    return list2

def main():
    list1 = genList1()
    list2 = genList2(list1)

选项2:这将是糟糕的编程实践

如果你想成为开发团队中其他人讨厌的人,你可以做很多这样的事情:

def genList1():
    global randlist
    randlist = [random.randint(2,25) for x in xrange(100)]
    for elem in randlist:
        print(elem, end = ' ')
    return randlist

def genList2():
    list2 = [x**2 for x in randlist if x % 2 == 0]
    return list2

def main():
    list1 = genList1()
    list2 = genList2()