从for循环返回的元素追加一个新列表

时间:2018-06-08 02:41:04

标签: python python-3.x append

有问题将gamepk附加到新列表然后设置和删除重复项。我的第一个问题就是制作新的清单。我以后可以担心这套。

import csv
import requests
import datetime
from pprint import pprint
import pendulum

start = pendulum.datetime(2016, 4, 3)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)

for dt in period.range('days'):
    day = dt.format('DD')
    month = dt.format('MM')
    year = dt.format('YYYY')
    the_date = str(month) + "/" + str(day) + "/" + str(year)

    try:
        req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # 
        get_gameIds = req.json()['data']['games']['game']

        for gameId in get_gameIds:
            gamepk = gameId['game_pk']
            new_gamepk = []
            for pk in gamepk:                
                new_gamepk.append(pk)
                print(new_gamepk)

在第二个到最后一个for循环之后打印gamepk会产生如下列表:

446877
452866
446911
446873
446870
446875
446872
446876
446867
446874
446879
446871

我觉得我应该将gamepk结果存储为列表..但我不确定。我要做的是然后将所有这些游戏块添加到一个新列表中,然后我可以调用set并删除重复项。我理解追加的概念,但显然无法让它正常工作。任何帮助和简要说明都有很长的路要走!

1 个答案:

答案 0 :(得分:2)

这个想法一般是:

  • 在最外层循环之外初始化一个空集合(list,set)
  • 找到所需的项目后,将其添加到集合中。

使用列表

import csv
import requests
import datetime
from pprint import pprint
import pendulum

start = pendulum.datetime(2016, 4, 3)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)

gamepks = []
for dt in period.range('days'):
    day = dt.format('DD')
    month = dt.format('MM')
    year = dt.format('YYYY')
    the_date = str(month) + "/" + str(day) + "/" + str(year)

    try:
        req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # 
        get_gameIds = req.json()['data']['games']['game']

        for gameId in get_gameIds:
            gamepk = gameId['game_pk']
            gamepks.append(gamepk)

使用套装

import csv
import requests
import datetime
from pprint import pprint
import pendulum

start = pendulum.datetime(2016, 4, 3)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)

gamepks = set()
for dt in period.range('days'):
    day = dt.format('DD')
    month = dt.format('MM')
    year = dt.format('YYYY')
    the_date = str(month) + "/" + str(day) + "/" + str(year)

    try:
        req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # 
        get_gameIds = req.json()['data']['games']['game']

        for gameId in get_gameIds:
            gamepk = gameId['game_pk']
            gamepks.add(gamepk)

了解范围界定非常重要。一旦循环退出,在内部范围内声明的变量(例如for循环内部)就会“消失”。这可能有助于指导您在循环结束后要初始化变量(在本例中为列表/集合)的位置。