1. 程式人生 > >Python實戰(八)

Python實戰(八)

一 實戰——列表操作

1 ex38.py

ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
    next_one = more_stuff.pop()
    print "Adding: ", next_one
    stuff.append(next_one)
    print "There are %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!

2 執行結果

PS E:\Python\exercise> 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

二 實戰——字典,可愛的字典

1 一些關於字典的例子

PS E:\Python\exercise> python
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print stuff['name']
Zed
>>> print stuff['age']
39
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco
>>> stuff[1] = "Wow"
>>> stuff[2] = "Neato"
>>> print stuff[1]
Wow
>>> print stuff[2]
Neato
>>> stuff
{'city': 'San Francisco', 2: 'Neato', 'name': 'Zed', 1: 'Wow', 'age': 39, 'height': 74}
>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 39, 'height': 74}

2 ex39.py

# create a mapping of state to abbreviation
states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
    'CA': 'San Francisco',
    'MI': 'Detroit',
    'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
    print "%s is abbreviated %s" % (state, abbrev)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
    print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
    print "%s state is abbreviated %s and has city %s" % (
        state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
    print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city

3 執行結果

PS E:\Python\exercise> python ex39.py
----------
NY State has:  New York
OR State has:  Portland
----------
Michigan's abbreviation is:  MI
Florida's abbreviation is:  FL
----------
Michigan has:  Detroit
Florida has:  Jacksonville
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
FL has the city Jacksonville
CA has the city San Francisco
MI has the city Detroit
OR has the city Portland
NY has the city New York
----------
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
Oregon state is abbreviated OR and has city Portland
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

4 hashmap.py

def new(num_buckets=256):
    """Initializes a Map with the given number of buckets."""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap
    
def hash_key(aMap, key):
    """Given a key this will create a number and then convert it to
    an index for the aMap's buckets."""
    return hash(key) % len(aMap)

def get_bucket(aMap, key):
    """Given a key, find the bucket where it would go."""
    bucket_id = hash_key(aMap, key)
    return aMap[bucket_id]
    
def get_slot(aMap, key, default=None):
    """
    Returns the index, key, and value of a slot found in a bucket.
    Returns -1, key, and default (None if not set) when not found.
    """
    bucket = get_bucket(aMap, key)
    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            return i, k, v
    return -1, key, default

def get(aMap, key, default=None):
    """Gets the value in a bucket for the given key, or the default."""
    i, k, v = get_slot(aMap, key, default=default)
    return v

def set(aMap, key, value):
    """Sets the key to the value, replacing any existing value."""
    bucket = get_bucket(aMap, key)
    i, k, v = get_slot(aMap, key)
    if i >= 0:
        # the key exists, replace it
        bucket[i] = (key, value)
    else:
        # the key does not, append to create it
        bucket.append((key, value))

def delete(aMap, key):
    """Deletes the given key from the Map."""
    bucket = get_bucket(aMap, key)
    for i in xrange(len(bucket)):
        k, v = bucket[i]
        if key == k:
            del bucket[i]
            break
    
def list(aMap):
    """Prints out what's in the Map."""
    for bucket in aMap:
        if bucket:
            for k, v in bucket:
                print k, v

5 ex39_test.py

import hashmap
# create a mapping of state to abbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')

# create a basic set of states and some cities in them
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set(cities, 'FL', 'Jacksonville')

# add some more cities
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')

# print out some cities
print '-' * 10
print "NY State has: %s" % hashmap.get(cities, 'NY')
print "OR State has: %s" % hashmap.get(cities, 'OR')

# print some states
print '-' * 10
print "Michigan's abbreviation is: %s" % hashmap.get(states, 'Michigan')
print "Florida's abbreviation is: %s" % hashmap.get(states, 'Florida')

# do it by using the state then cities dict
print '-' * 10
print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan'))
print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida'))

# print every state abbreviation
print '-' * 10
hashmap.list(states)

# print every city in state
print '-' * 10
hashmap.list(cities)
print '-' * 10
state = hashmap.get(states, 'Texas')
if not state:
    print "Sorry, no Texas."
# default values using ||= with the nil result
# can you do this on one line?
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city

6 執行結果

PS E:\Python\exercise> python ex39_test.py
----------
NY State has: New York
OR State has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
California CA
New York NY
Michigan MI
Oregon OR
Florida FL
----------
FL Jacksonville
NY New York
CA San Francisco
OR Portland
MI Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

相關推薦

Python實戰

一 實戰——列表操作 1 ex38.py ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there are not 10 things in that list. Let's f

Spring Boot 揭秘與實戰 發布與部署 - 遠程調試

hat artifact pom.xml href span 發布 作者 elf ava 文章目錄 1. 依賴 2. 部署 3. 調試 4. 源代碼 設置遠程調試,可以在正式環境上隨時跟蹤與調試生產故障。 依賴 在 pom.xml 中增加遠程調試依賴。 <pl

Selenium2+Python3.6實戰:定位下拉菜單出錯,如何解決?用select或xpath定位。

排查 會有 有時 ide 導入 python3 很好 沒有 元素 在登錄界面,有時候會有幾種不同的角色,針對不同角色定位到的信息是不一樣的。查詢資料知道定位下拉框的元素有兩種方式:Xpath和select。 但是使用xpath定位時,user定位到了,登錄的時候卻是調用的a

Spring實戰bean裝配的運行時值註入——屬性占位符和SpEL

裝配 getprop 直接 通過 mic lang 進行 ole 實戰   前面涉及到依賴註入,我們一般哦都是將一個bean引用註入到另一個bean 的屬性or構造器參數or Setter參數,即將為一個對象與另一個對象進行關聯。   bean裝配的另一個方面是指將一個值註

Python筆記:web開發

自定義 服務器 gpo unix系統 運行 tps rom request 不知道 #本文是在Windows環境下,Unix系統應該還要設置2個東西 (一) 采用MVC設計web應用 遵循 模型-視圖-控制器(model-view-controlle) 模型:

python入門捕獲異常及內置參數

內置時間參數 python3 捕獲異常的的語法 try: 運行代碼 except(名稱) 出現異常的運行代碼 else 沒有出現異常的運行代碼 raise 引發一個異常 finally 不論有沒有異常都運行 例子: try: 2/0 except Exception as e:(商量的語法)

python基礎:函數

int 工具 位置 spa 不能 lte for fun 接下來 函數就是將一些語句集合在一起的部件,他們能夠不止一次的程序中運行,函數還能夠計算出一個返回值,並能夠改變作為函數輸入的參數。而這些參數在代碼運行時每次都不同。以函數的形式去編寫一個操作可以使它

機器學習實戰分類迴歸樹CARTClassification And Regression Tree

目錄 0. 前言 1. 迴歸樹 2. 模型樹 3. 剪枝(pruning) 3.1. 預剪枝 3.2. 後剪枝 4. 實戰案例 4.1. 迴歸樹 4.2. 模型樹

Python基礎之 set 集合

全部測試程式碼 #!/usr/bin/env python3 #_*_ conding:utf-8 _*_ #set是一組key的集合,但是沒有重複的key,重複的值自動被過濾 # 建立一個set,以list作為輸入集合,輸出的資料用大括號{}顯示,且是無序的 s=set([1

Python實戰

一 實戰——讀寫檔案 1 ex16.py from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want

Python實戰

一 實戰——輸入 1 ex11.py print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you

Python實戰

一 實戰——字串和文字 1 ex6.py # -- coding: utf-8 -- x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who

重拾Python學習----------IO程式設計

本文參考:廖雪峰的官方網站:https://www.liaoxuefeng.com 檔案讀寫 讀檔案 讀檔案的模式開啟一個檔案物件open() 一次讀取檔案的全部內容read() 關閉檔案close() >>> f = open('/Use

OpenCV-Python實戰Ubuntu18.04實現人臉檢測+輸出抓圖時間

參考:python+opencv計算程式碼執行時間:time庫和opencv自帶方法getTickCount cv2級聯分類器CascadeClassifier 一、Haar特徵分類器介紹 Haar特徵分類器就是一個XML檔案,該檔案中會描述人體各個部位的Haar特徵值。包括人

微服務Springcloud超詳細教程+實戰

本人正在找深圳Java實習工作,求大佬帶飛 QQ:1172796094 如在文件中遇到什麼問題請聯絡作者 —————————————————————————————————————— 消費者從Eureka獲取服務 接下來我們修改consumer-demo,嘗試從EurekaServe

Python實戰

一 實戰——第一個程式 1 ex1.py print "Hello World!" print "Hello Again" print "I like typing this." print "This is fun." print 'Yay! Printing.' pr

Python實戰

一 實戰——函式的返回值 1 ex21.py def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subt

Python實戰

一 實戰——恭喜你,可以進行一次考試了 1 ex26.py def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ')

Python實戰

一 實戰——做出決定 1 ex31.py print "You enter a dark room with two doors. Do you go through door #1 or door #2?" door = raw_input("> ") if do

Node.js從入門到實戰Solr的層級

參考:Node.js從入門到實戰(七)Solr查詢規則總結 一、Solr的層級 Solr作為關鍵的搜尋元件,在整個系統中的架構如下圖所示: Solr的索引服務是為了提高搜尋的效率,一般而言Solr需要配合Nosql DB使用,作為與NoSQL DB相互獨立的補充,在能夠