python返回函数

python返回函数,python,return,Python,Return,我有一个程序生成一个由10个1-5之间的随机数组成的列表,然后计算每个数出现的次数,然后创建一个新列表,删除重复项。我一直认为某些全局名称没有定义。我似乎对返回函数感到困惑。不过我需要这种格式,所以我不能只在每个函数的末尾放print语句。有什么帮助吗 def main(): """print output of program""" firstList= [] randomTen(firstList) countInts(firstList) remov

我有一个程序生成一个由10个1-5之间的随机数组成的列表,然后计算每个数出现的次数,然后创建一个新列表,删除重复项。我一直认为某些全局名称没有定义。我似乎对返回函数感到困惑。不过我需要这种格式,所以我不能只在每个函数的末尾放print语句。有什么帮助吗

def main():
    """print output of program"""
    firstList= []
    randomTen(firstList)
    countInts(firstList)
    removeDuplicates(firstList)
    print(firstList)
    print('The number of times one appears is', ones)
    print('The number of times two appears is', twos)
    print('The number of times three appears is', threes)
    print('The number of times four appears is', fours)
    print('The number of times five appears is', fives)
    print(secondList)


def randomTen(firstList):
    """return list of ten integers"""
    for num in range(1,11):
        x= int(random.randint(1,5))
        firstList.append(x)
    return firstList


def countInts(firstList):
    """count the number of times each integer appears in the list"""
    ones= firstList.count(1)
    twos= firstList.count(2)
    threes= firstList.count(3)
    fours= firstList.count(4)
    fives= firstList.count(5)
    return ones, twos, threes, fours, fives

def removeDuplicates(firstList):
    """return list of random integers with the duplicates removed"""
    secondList=set(firstList)
    return secondList

问题是您忽略了函数的返回值。比如说,

countInts(firstList)
应该读

ones, twos, threes, fours, fives = countInts(firstList)
没有这一点,
main()
中就不存在
one

其他函数也是如此(除了
randomTen()
,它除了返回
firstList
,还就地修改它)。

完全正确,您需要将函数的返回值指定给局部变量

这就是说,这里有一个完成同样任务的更具Python风格的方法

from collections import Counter
from random import randint

nums = [randint(1, 5) for _ in range(10)]
counts = Counter(nums)
uniq_nums = set(nums) # or list(counts.keys())
要显示值,请执行以下操作:

print nums
for word, num in (('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)):
    print 'The number of times %s appears is %s' % (word, counts[num])
print uniq_nums
其中打印:

[4, 5, 1, 4, 1, 2, 2, 3, 2, 1]
The number of times one appears is 3
The number of times two appears is 3
The number of times three appears is 1
The number of times four appears is 2
The number of times five appears is 1
set([1, 2, 3, 4, 5])

张贴您收到的回溯和错误消息。它说的是一,但我想如果它指的是一、二、三、四、五和第二个列表,但停止在onesTraceback(最近的调用最后一次):文件“”,第1行,在main()文件“/Users/tinydancer9454/Documents/randomInts.py”,第26行,在主打印中(“一次出现的次数为”,个)名称错误:未定义全局名称“个”