-1

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

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
4

2 回答 2

3

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

countInts(firstList)

应该读

ones, twos, threes, fours, fives = countInts(firstList)

没有这个,ones 等人不存在main()

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

于 2013-03-11T16:42:54.000 回答
1

NPE 的答案完全正确,您需要将函数的返回值分配给局部变量。

也就是说,这里有一种更 Pythonic 的方式来完成相同的任务。

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])
于 2013-03-11T16:54:38.437 回答