If语句似乎被Write操作忽略了

时间:2016-08-22 03:40:22

标签: python

我在这里要做的是将一个神奇宝贝的经纬度写入文本文件(如果它尚不存在的话)。由于我使用无限循环,我添加了一个if状态,可以防止添加已经存在的坐标对。 请注意,我还有一个列表,用于存储相同的信息。列表工作,因为没有添加重复。(通过检查)但是,文本文件具有相同的坐标一遍又一遍,即使它理论上不应该,因为它包含在与列表相同的if-block中。

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

2 个答案:

答案 0 :(得分:2)

如果您不希望它们在每次迭代时都重置,则需要将SightingCoordinates变量放在while循环之外。

但是,代码还有很多问题。没有尝试,这就是我发现的:

  1. while循环没有退出条件。请不要在糟糕的网站上这样做。你基本上是垃圾邮件请求。
  2. file.close应为file.close(),但总的来说,您只需要打开一次文件,而不是每次循环迭代。打开一次,并在完成后关闭(假设您将添加退出条件)。
  3. 0response.json()[0:])切片是不必要的。默认情况下,列表从索引0开始。这可能是一种复杂的获取新列表的方式,但这似乎没必要。
  4. Coordinates不应该是100 None s的硬编码列表。只需使用set跟踪现有坐标。
  5. 完全摆脱Sighting。如果您一遍又一遍地重新发出请求,那就没有意义了。如果你想从一个回复中迭代神奇宝贝,如果你需要索引,请使用enumerate
  6. snake case用于Python变量通常是一种好习惯。

答案 1 :(得分:0)

试试这个:

#!/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