logo
Loading...

print(doc['cwbopendata']['dataset']['locations']['location']) 出現TypeError:list indices must be integars or slices,not錯誤 - Cupoy

您好想請問以下程式碼該如何修正?print(doc['cwbopendata']['dataset'...

xml

print(doc['cwbopendata']['dataset']['locations']['location']) 出現TypeError:list indices must be integars or slices,not錯誤

2020/02/24 下午 05:08
Python網路爬蟲討論版
皓文劉
觀看數:6
回答數:2
收藏數:0
xml

您好

想請問以下程式碼該如何修正?

print(doc['cwbopendata']['dataset']['locations']['location'])都能正常運行

但是加了第五層就不行

我應該注意什麼呢?

謝謝您

回答列表

  • 2020/02/24 下午 05:36
    張維元 (WeiYuan)
    贊同數:0
    不贊同數:0
    留言數:1

    嗨,你可以試著把 「doc['cwbopendata']['dataset']['locations']['location']」 這一個東西印出來,你會發現它其實是一個 List 的型態,所以你無法直接用 ['locationName'] 存取它。

  • 2020/02/27 下午 02:32
    張維元 (WeiYuan)
    贊同數:1
    不贊同數:0
    留言數:0

    第二層的 x[1] 是一個 Dict,可以用 KEY 來取資料,例如: 嗨,這邊我會建議你一層一層取出資料,邊印邊看的方式進行。


    首先先複習一下,在 Python 程式中常見的兩種結構:


    1. List: l = ['a', 'b', 'c'],我們可以利用 l[0] 取出 第 0 個位置的資料 'a'

    2. Dict: d = {'a': 111, 'b': '222},我們可以利用 d['a'] 取出 key = a 的資料 111


    那我們來看一個複雜一點的資料(三層):


    x = [{'a': ['1', '3', '5']}, {'a': ['2', '4', '6'], 'b': [0, 1, 2, 3, 4, 5]}]


    最外層是一個 List,我們可以用 位置 來取資料,例如:


    x[0] => {'a': ['1', '3', '5']}

    x[1] => {'a': ['2', '4', '6'], 'b': [0, 1, 2, 3, 4, 5]}


    第二層的 x[1] 是一個 Dict,可以用 KEY 來取資料,例如: 


    x[1]['a'] => ['2', '4', '6']

    x[1]['b'] => [11, 22, 33, 44, 55]


    第三層的 x[1]['b'] 是一個 List,可以用 位置 來取資料,例如: 


    x[1]['b'][0] => 11

    x[1]['b'][2] => 33


    總結來說,大概就這樣看資料原本的資料,一層一層取出你要的部分。原本的資料建議可以從瀏覽器直接開啟 xml 檔案觀察。