【问题标题】:read through a dictionary for int通过字典阅读 int
【发布时间】:2017-07-25 14:01:34
【问题描述】:

我的代码有些问题。当我尝试运行它时,我不断收到一条错误消息,我不知道为什么。

有人可以帮忙吗?

import requests
import argparse
import json
from urllib.request import urlopen


url = "http://hn.algolia.com/api/v1/search_by_date?tags=story&numericFilters=created_at_i>1488196800,created_at_i<1488715200"
r = urlopen(url)
data = r.read().decode("utf-8")
j_data = json.loads(data)

def build_structure(data, d=[]):
    if 'hits' in data:
        for t in data['hits']:
            d.append({'title' : t.get('title'), 'point' : t.get('points')})
            build_structure(t,d)
    return d

j = build_structure(j_data)
print(j)
word = "Python"
points = "2"
def structure_search_by_title(data, word, s=[]):
    for c in data:
        if word in c['title']:
            s.append({'title' : c.get('title')})
    return s

def structure_search_by_points(data, points, s=[]):
    for c in data:
        if points in c['point']:
            s.append({'Title of the article is' : c.get('title')})


k = structure_search_by_title(j, word)
l = structure_search_by_points(j, points)
print(k)
print(l)

这是我遇到的错误

File "C:/Users/PycharmProjects/Project1/Project1.py", line 36, in <module>
l = structure_search_by_points(j, points)
File "C:/Users/PycharmProjects/Project1/Project1.py", line 31, in structure_search_by_points
if points in c['point']:
TypeError: argument of type 'int' is not iterable

【问题讨论】:

  • 你应该给你的变量起更有意义的名字。它使调试程序变得更加容易。

标签: python json dictionary typeerror


【解决方案1】:

在API返回的JSON中,points是一个整数,不是字符串,所以c['point']是一个整数。所以写起来没有任何意义:

if points in c['point']:

因为c['point'] 不是您可以搜索的列表或字符串。您应该只使用一个简单的相等测试。

def structure_search_by_points(data, points, s=[]):
    points = int(points)
    for c in data:
        if points == c['point']:
            s.append({'Title of the article is' : c.get('title')})
    return s

【讨论】:

  • 这不起作用,我仍然收到相同的错误消息
  • 我不明白这是怎么回事。您确定已保存更改吗?
  • 我知道我现在做错了什么,谢谢大家的帮助!
【解决方案2】:

以下是您的代码的一些注意事项:

import requests
import argparse
import json
from urllib.request import urlopen


url = "http://hn.algolia.com/api/v1/search_by_date?tags=story&numericFilters=created_at_i>1488196800,created_at_i<1488715200"
r = urlopen(url)
data = r.read().decode("utf-8")
j_data = json.loads(data)

def build_structure(data, d=[]):   # using a mutable as an initialiser
                                   # are you sure you know what you're doing?
    if 'hits' in data:
        for t in data['hits']:
            d.append({'title' : t.get('title'), 'point' : t.get('points')})
            build_structure(t,d)   # are you sure you want to call the
                                   # function recursively? (is the key
                                   # "hits" expected to occur in data["hits"]?
    return d

j = build_structure(j_data)
print(j)
word = "Python"
points = "2"
def structure_search_by_title(data, word, s=[]): # again, a mutable initialiser
    for c in data:
        if word in c['title']:
            s.append({'title' : c.get('title')}) # can use c['title'] here since
                                                 # you know 'title' is in c
    return s

def structure_search_by_points(data, points, s=[]): # another mutable
                                                    # initialiser
    for c in data:
        if points in c['point']:      # according to the error message
                                      # c['point'] is a single number
                                      # but 'in' expects something it can
                                      # search through, like a list
                                      # on top of that you points is a string
                                      # so the two cannot be compared directly
            s.append({'Title of the article is' : c.get('title')})


k = structure_search_by_title(j, word)
l = structure_search_by_points(j, points)
print(k)
print(l)

【讨论】:

  • 我为更简洁的代码做了这些初始化程序,以便任何程序员都可以通过它并了解他们在做什么。至于带有 ['hits'] 的行,我从 json 解析返回的原始字典是嵌套的,为了从嵌套字典中查找所有数据,我必须使其递归,以便找到隐藏的数据。我只是在查找隐藏数据中的整数时遇到了麻烦,而且我一生都无法弄清楚如何让它通过排序数组 j 读取并返回与点值匹配的标题值。
  • @KRose 我不确定您是否完全掌握了可变初始化程序的问题(以防您忽略了这一点),重点是可变的。如果您两次调用此类函数并且它修改了变量,则该变量不会被重置,例如,如果您在第一次调用期间填写您的s=[],则第二次它不会为空。更糟糕的是,由于您正在返回 s,所以两个调用者都将收到 相同的 对象。所以如果第一个调用者对s做了什么,第二个调用者的s也会改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多