Published 9月 17, 2018 by with 0 comment

習題38 - 列表的操作




用Notepad++打下列的程式碼,
另存為ex38.py. 我附上中文注釋方便好讀.
# 先定義ten_things, 但不夠10樣東西, 所以後面要加上去.
ten_things = "Apples Oranges Crows Telephone Light Sugar"

print("Wait there are not 10 things in that list. Let's fix that.")

# 把ten_things以空格分開, 並定義為stuff.
# 這個stuff 長度是以字為單位, 所以它的長度為6, 原本是42
stuff = ten_things.split(' ')

# 定義一個列表more_stuff
more_stuff = ["Day", "Night", "Song", "Frisbee",
                "Corn", "Banana", "Girl", "Boy"]

# 當stuff 的長度不為10, 則
while len(stuff) != 10:
    # 將more_stuff取出每一個字, 並將該字定義為next_one.
    next_one = more_stuff.pop()
    # 將取出來的字印出來.
    print("Adding: ", next_one)
    # 把他加進stuff列表中.
    # !!! 這邊很有趣, 單元是反序加進來的 !!!
    stuff.append(next_one)
    # 印出stuff列表的長度.
    print(f"There are {len(stuff)} items now")

# 印出stuff列表的內容.
print("There we go: ", stuff)

print("Let's do some things with stuff.")

# 印出stuff列表的第二個內容
print(stuff[1])
# 印出stuff列表的倒數第一個內容
print(stuff[-1]) # whoa! fancy
# 取出stuff列表的第一個內容
print(stuff.pop())
# 把空格加入stuff
print(' '.join(stuff)) # what! cool!
# 印出stuff列表的第4-6個(不包括第6個)的內容, 並用#分開
print('#'.join(stuff[3:5])) # super stellar!

然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python ex38.py
Wait there are not 10 things in that list. Let's fix that.
Adding:  Boy
There are 7 items now
Adding:  Girl
There are 8 items now
Adding:  Banana
There are 9 items now
Adding:  Corn
There are 10 items now
There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light

C:\Users\Peter\Desktop\Python\LP3THW>

完成


最初發表 / 最後更新: 2018.09.17 / 2018.09.17

0 comments:

張貼留言