繁体   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