zoukankan      html  css  js  c++  java
  • Python Chapter 10: 列表 Part2

    10.3 实例研究:乐透数

    编写程序决定输入数字是否涵盖了1-99之间的所有整数:

    # Create a list of 99 Boolean elements with value False
    isCovered = 99 * [False]
    endOfInput = False
    while not endOfInput:
        s = input("Enter a line of numbers separated by spaces: ")
        items = s.split()
        lst = [eval(x) for x in items]
    
        for number in lst:
            if number == 0:
                endOfInput = True
            else:
                isCovered[number - 1] = True
    
    allCovered = True
    for i in range(99):
        if not isCovered[i]:
            allCovered = False
            break
    if allCovered:
        print("The tickets cover all numbers")
    else:
        print("The tickets don't cover all numbers")
    

    10.4 实例研究:一副扑克牌

    在一副扑克牌中随机抽出四张并显示花色与数字:

    # Create a deck of cards
    deck = [x for x in range(52)]
    
    # Create suits and ranks lists
    suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
    ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
    
    import random
    random.shuffle(deck)
    
    for i in range(4):
        suit = suits[deck[i] // 13]
        rank = ranks[deck[i] % 13]
        print("Card number", deck[i], "is the", rank, "of", suit)
    

    10.5 扑克牌图形用户界面

    给出一个图形用户界面,单机shuffle按钮,显示四张随机扑克牌的图像:

    from tkinter import *
    import random
    
    class DeckOfCardsGUI:
        def __init__(self):
            window = Tk()
            window.title("Pick Four Cards Radnomly")
    
            self.imageList = []
            for i in range(1, 53):
                self.imageList.append(PhotoImage(file = "image/card/" + str(i) + ".gif"))
    
            frame = Frame(window);
            frame.pack()
    
            self.labelList = []
            for i in range(4):
                self.labelList.append(Label(frame, image = self.imageList[i]))
                self.labelList[i].pack(side = LEFT)
    
            Button(window, text = "Shuffle", command = self.shuffle).pack()
    
            window.mainloop()
    
        def shuffle(self):
            random.shuffle(self.imageList)
            for i in range(4):
                self.labelList[i]["image"] = self.imageList[i]
    
    DeckOfCardsGUI()
    

    10.6 复制列表

    想到复制列表时,你可能会尝试这条语句:

    list2 = list1
    

    实际上,这样只是让list2指向list1的一个引用,原list2的内容就成了垃圾,被Python自动收集重新利用。因此此时list2与list1实际上会指向同一块内容。
    为了达到真正赋值的效果,可以采用:

    list2 = [x for x in list1]
    list2 = [] + list1
    

    10.7 将列表传递给函数

    )列表传递给函数后值可变

    由于列表是一个可变对象,列表的内容可能在函数调用后发生改变:

    def main():
        x = 1
        y = [1, 2, 3]
    
        m(x, y)
    
        print("x is", x)
        print("y[0] is", y[0])
    
    def m(number, numbers):
        number = 1001
        numbers[0] = 5555
    
    main()
    

    该程序运行结果如图所示:

    如图,由于函数对简单变量进行传值调用,x的值在函数调用后并不发生改变。而y这个列表的值就发生了改变

    )默认参数

    Python中的默认参数只会声明一次,亦即生成函数的默认参数后此参数值将一直保留,在后续调用中保留其值:

    def add(x, lst = []):
        if x not in lst:
            lst.append(x)
    
        return lst
    
    def main():
        list1 = add(1)
        print(list1)
        list2 = add(2)
        print(list2)
        list3 = add(3, [11, 12, 13, 14])
        print(list3)
        list4 = add(4)
        print(list4)
    
    main()
    

    此程序运行结果如下所示:

    由此可见,在第二次、第四次调用add()时,原先创建的默认参数lst里的值还存在,故在调用后会累积在列表中。
    若想每次调用后默认参数都回到[],使用如下方法:

    def add(x, lst = None):
        if lst == None:
            lst = []
        if x not in lst:
            lst.append(x)
    
        return lst
    
    def main():
        list1 = add(1)
        print(list1)
        list2 = add(2)
        print(list2)
        list3 = add(3, [11, 12, 13, 14])
        print(list3)
        list4 = add(4)
        print(list4)
    
    main()
    

    10.8 从函数返回一个列表

    函数返回一个列表时,就会返回这个列表的引用值


    10.9 实例研究:统计每个字母的出现次数

    随机生成100个小写字母并统计他们出现的频数:

    import RandomCharacter
    
    def main():
        chars = createList()
    
        print("The lowercase letters are:")
        displayList(chars)
    
        counts = countLetters(chars)
    
        print("The occurences of each letter are:")
        displayCounts(counts)
    
    def createList():
        chars = []
    
        for i in range(100):
            chars.append(RandomCharacter.getRandomLowerCaseLetter())
    
        return chars
    
    def displayList(chars):
        for i in range(len(chars)):
            if (i + 1) % 20 == 0:
                print(chars[i])
            else:
                print(chars[i], end = ' ')
    
    def countLetters(chars):
        counts = 26 * [0]
    
        for i in range(len(chars)):
            counts[ord(chars[i]) - ord('a')] += 1
    
        return counts
    
    def displayCounts(counts):
        for i in range(len(counts)):
            if (i + 1) % 10 == 0:
                print(counts[i], chr(i + ord('a')))
            else:
                print(counts[i], chr(i + ord('a')), end = ' ')
    
    main()
    

  • 相关阅读:
    hdu 3018
    poj 1833 排列
    poj 1256 Anagram
    CF 548B Mike and Fun
    CF 548A
    【冰茶几专题】F
    【冰茶几专题】C
    535 C.Tavas and karafs
    [WA]cf 534 D. Handshakes
    cf 534C. Polycarpus' Dice
  • 原文地址:https://www.cnblogs.com/fsbblogs/p/9741736.html
Copyright © 2011-2022 走看看