9
import random  

#----------------------------------------------#
def main():  
    create_list_and_find_max_and_min(10)  
    the_smart_way()
#----------------------------------------------#
def create_list_and_find_max_and_min(n):
    global my_array
    my_array = []
    n = input("How many numbers do you want in your array?:")
    for i in range(n):
        my_array.append(random.randint(1,n))
    print "My array is:", my_array
    #----------------------------------------------#
    min = my_array[0]
    for number in my_array:
    if min > number:
        min = number
    print "The minimum value in the array is:", min
    #----------------------------------------------#
    max = my_array[0]
    for number in my_array:
        if max < number:
        max = number
    print "The maximum value in the array is:", max
#----------------------------------------------#
def the_smart_way():
    # "This one uses the built-in Python functions for min/max..."
    min_my_array = min(my_array)
    max_my_array = max(my_array)
    return min_my_array, max_my_array
#----------------------------------------------#
if __name__ == '__main__':
    main()

我对使用 Python 还是很陌生。我通常听说在编程时使用全局变量是一种不好的做法。那么我在这里尝试做的事情还有其他选择吗?哪个是在另一个函数中使用变量“my_array”?谢谢!

4

3 回答 3

15

是的,有两种选择。

首先,您可以传递值而不是使用全局变量。比如create_list_and_find_max_and_min可以在本地创建数组并返回,然后可以传入the_smart_way:

import random  

#----------------------------------------------#
def main():  
    my_array = create_list_and_find_max_and_min(10)  
    print the_smart_way(my_array)
#----------------------------------------------#
def create_list_and_find_max_and_min(n):
    my_array = []
    n = input("How many numbers do you want in your array?:")
    for i in range(n):
        my_array.append(random.randint(1,n))
    print "My array is:", my_array
    #----------------------------------------------#
    min = my_array[0]
    for number in my_array:
        if min > number:
            min = number
    print "The minimum value in the array is:", min
    #----------------------------------------------#
    max = my_array[0]
    for number in my_array:
        if max < number:
            max = number
    print "The maximum value in the array is:", max
    return my_array
#----------------------------------------------#
def the_smart_way(my_array):
    # "This one uses the built-in Python functions for min/max..."
    min_my_array = min(my_array)
    max_my_array = max(my_array)
    return min_my_array, max_my_array
#----------------------------------------------#
if __name__ == '__main__':
    main()

其次,您可以创建一个封装数据的类以及对该数据进行操作的函数:

import random  

#----------------------------------------------#
class MyArrayClass(object):
    def create_list_and_find_max_and_min(self, n):
        self.my_array = []
        n = input("How many numbers do you want in your array?:")
        for i in range(n):
            self.my_array.append(random.randint(1,n))
        print "My array is:", self.my_array
        #----------------------------------------------#
        min = self.my_array[0]
        for number in self.my_array:
            if min > number:
                min = number
        print "The minimum value in the array is:", min
        #----------------------------------------------#
        max = self.my_array[0]
        for number in self.my_array:
            if max < number:
                max = number
        print "The maximum value in the array is:", max
    #----------------------------------------------#
    def the_smart_way(self):
        # "This one uses the built-in Python functions for min/max..."
        min_my_array = min(self.my_array)
        max_my_array = max(self.my_array)
        return min_my_array, max_my_array
#----------------------------------------------#
def main():
    my_array = MyArrayClass()
    my_array.create_list_and_find_max_and_min(10)  
    print my_array.the_smart_way()
#----------------------------------------------#
if __name__ == '__main__':
    main()

您可能应该了解全局变量是不好的做法的原因。

假设您要创建两个数组。使用全局变量,第二个将替换第一个,这将永远消失。

create_list_and_fix_max_and_min(10)
create_list_and_fix_max_and_min(20)
# No way to operate on the original array!

使用局部变量,您可以存储它们:

my_array_1 = create_list_and_fix_max_and_min(10)
my_array_2 = create_list_and_fix_max_and_min(20)
the_smart_way(my_array_1)

使用对象提供了同样的好处;两者的区别最终归结为操作是否是数据含义的一部分,或者数据是否独立,操作是否通用。(或者,有时,无论你是功能性势利小人还是 OO 势利小人……)

于 2012-07-12T23:49:27.143 回答
2

函数对对象做事,然后返回结果。您希望使函数保持简单,并在函数之外执行所有逻辑和处理。这将消除对全局变量的需求,并使您的代码更容易阅读。

话虽如此,这就是我将如何解决您的问题:

import random  

def random_list(n=None):
  n = n or int(raw_input('How many numbers do you want in your list? '))    

  return [random.randint(1, n) for i in range(n)]

if __name__ == '__main__':
  my_list = random_list(10)
  minimum, maximum = min(my_list), max(my_list)

  print 'My list is ', my_list
  print 'The minimum value in the list is ', minimum
  print 'The maximum value in the list is ', maximum
于 2012-07-13T00:05:05.310 回答
1

这是我将如何做到这一点:

import random  

#----------------------------------------------#
def main():
    # note that input can be dangerous since it evaluates arbitrary code
    n = int(raw_input("How many numbers do you want in your array?: "))
    my_list = [random.randint(1, n) for _ in range(n)]
    find_max_and_min(my_list)  
    the_smart_way(my_list)
#----------------------------------------------#
def find_max_and_min(seq):
    print "My array is:", seq
    #----------------------------------------------#
    min_num = seq[0] # Don't want to use same names as bultins here
    for number in seq:
        if number < min_num:
            min_num = number
    print "The minimum value in the array is:", min_num
    #----------------------------------------------#
    max_num = seq[0]
    for number in seq:
        if number > max_num:
            max_num = number
    print "The maximum value in the array is:", max_num
#----------------------------------------------#
def the_smart_way(seq):
    # "This one uses the built-in Python functions for min/max..."
    # No need for temp variables here
    print min(seq), max(seq)
#----------------------------------------------#
if __name__ == '__main__':
    main()
于 2012-07-12T23:57:24.143 回答