写操作似乎忽略了Ifstatement

2024-09-27 21:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里要做的是,如果口袋妖怪还不存在的话,把它的纬度和经度写进一个文本文件。因为我使用的是一个无限循环,所以我添加了一个if状态,它阻止添加已经存在的一对坐标。 注意,我还有一个存储相同信息的列表坐标。列表的工作原理是不添加重复项。(通过检查)但是,文本文件具有重复添加的相同坐标,即使理论上不应该,因为它包含在与列表相同的if块中。你知道吗

import requests

pokemon_url = 'https://pogo.appx.hk/top'

while True:
    response = requests.get(pokemon_url)
    response.raise_for_status()

    pokemon = response.json()[0:]

    Sighting = 0
    Coordinates = [None] * 100

    for num in range(len(pokemon)):
        if pokemon[num]['pokemon_name'] == 'Aerodactyl':
            Lat = pokemon[num]['latitude']
            Long = pokemon[num]['longitude']
            if (Lat, Long) not in Coordinates:
                Coordinates[Sighting] = (Lat, Long)
                file = open("aerodactyl.txt", "a")
                file.write(str(Lat) + "," + str(Long) + "\n")
                file.close()
                Sighting += 1

为了清楚起见,这是输出 For clarity purposes, this is the output


Tags: inurl列表forifresponserequestsnum
2条回答

试试这个:

#!/usr/bin/env python

import urllib2
import json

pokemon_url = 'https://pogo.appx.hk/top'

pokemon = urllib2.urlopen(pokemon_url)

pokeset = json.load(pokemon)

Coordinates = [None] * 100

for num in range(len(pokeset)):
    if pokeset[num]['pokemon_name'] == 'Aerodactyl':
        Lat = pokeset[num]['latitude']
        Long = pokeset[num]['longitude']
        if (Lat, Long) not in Coordinates:
            Coordinates.append((Lat, Long))
            file = open("aerodactyl.txt", "a")
            file.write(str(Lat) + "," + str(Long) + "\n")
            file.close

如果您不想在每次迭代时重置SightingCoordinates变量,则需要将它们放在while循环之外。你知道吗

然而,代码有很多错误。不用尝试,我发现:

  1. 您没有while循环的退出条件。请不要这样对这个可怜的网站。你基本上是在发送垃圾邮件。你知道吗
  2. file.close应该是file.close(),但总的来说,您应该只需要打开一次文件,而不是每次循环都打开一次。打开一次,完成后关闭(假设您将添加一个退出条件)。你知道吗
  3. 0response.json()[0:])切片是不必要的。默认情况下,列表从索引0开始。这可能是一个复杂的方式来获得一个新的名单,但这似乎没有必要在这里。你知道吗
  4. Coordinates不应是100None的硬编码列表。只需使用^{}跟踪现有坐标即可。你知道吗
  5. 彻底摆脱Sighting。如果你一次又一次地发出请求是没有意义的。如果您想从一个响应遍历pokémon,如果需要索引,请使用^{}。你知道吗
  6. 对Python变量使用snake case通常是一种很好的做法。你知道吗

相关问题 更多 >

    热门问题