簡體   English   中英

如何在推文中不包含任何值的情況下獲取列表中的所有迭代?

[英]How to get all the iterations in a list with none values included from a tweet?

我在“ tweets”列表中設置了帶有10個詞典的tweets。 每個字典都有幾條推文。 第一條推文有100條,其余9條各有15條。 我需要所有詞典中每條推文的位置。 當我嘗試迭代列表中的值時,它顯示此錯誤。

if (type(tweets[j]['statuses'][k]['place']['name'])) != None:

TypeError: 'NoneType' object is not subscriptable

我用於迭代的代碼是

for j in range (0,10):
    while j == 0:
       for k in range(0,100):
          st1 = tweets[j]['statuses'][k]['place']['name']
          print(st1)

我嘗試使用“過濾器”取出“無”值,即使那是行不通的。 並非每條推文都有標記的位置。 因此它沒有值。 我需要打印標記的推文的位置。

您是否嘗試過檢查“位置”鍵是否首先可用。 我從您的代碼中看到您正在檢查['place'] ['name']

您能否使用不帶['name']的以下過濾器邏輯來測試您的邏輯:

...
if (isinstance(tweets[j].get('statuses',[])[k].get('place', {}))) == dict:
...

twitter api返回json,這是Python中的dictionary類型。 使用dict[key]語法調用鍵時,這稱為subscripting 現在,對dict對象的嵌套調用依賴於該對象為字典類型:

dict[a][b]依賴於dict[a]是具有鍵b的字典。 如果dict[a]是不同的類型,例如Noneint ,則它不能下標。 這意味着不一定需要該類型的get屬性。 解決此問題的簡單方法如下:

check = tweets[j]['statuses'][k]['place']

if isinstance(check, dict):
    # do things

這可以確保checkdict類型的,因此可以用密鑰下標

編輯:請注意,使用dict[key]語法對KeyErrors 並不安全。 如果要避免這些,請使用get

my_dictionary = {'a': 1, 'b': 2}
my_dictionary['c']     # Raises KeyError: 'c' not in dictionary
my_dictionary.get('c') # returns None, no KeyError

它采用dict.get(key, <return_value>) ,其中return_value默認為None

為了使您的程序更具可讀性並避免不可避免的無限循環,請拋棄while循環:

# This will get individual tweets
for tweet in tweets:

    # Returns all statuses or empty list
    statuses = tweet.get('statuses', [])
    for status in statuses:
        if not isinstance(status, dict):
            continue # will jump to next iteration of inner for loop

        # Will be a name or None, if empty dict is returned from place
        name = status.get('place', {}).get('name')
        if name:
            print(name)
for element in tweets:
    for s in element.get('statuses'):
       place = s.get('place')
       print(place['name'])

這樣就解決了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM