根据输入的参数数重复输出

时间:2017-07-03 00:06:08

标签: python

非常新的Python,我的知识范围是我刚刚在过去几个小时内构建的:

from sys import argv
import requests
import xml.etree.ElementTree as ET

script, gameid = argv

game = requests.get("http://boardgamegeek.com/xmlapi/game/" + (gameid))
r = game.text
root = ET.fromstring(r)
boardgame = root.findall('boardgame')
for b in boardgame:
    name = b.find('name').text
    year = b.find('yearpublished').text
    mech = b.find('boardgamemechanic').text
    cat = b.find('boardgamecategory').text
    print (name,",",year,",",mech,",",cat)

这就是我想做的事情,就是根据用户输入给我上面的四条信息。

我想知道的是,是否可以多次运行此脚本,其中n是在cmd行输入的参数数量?

输出如下所示:

C:\Python>bgg.py 822
Carcassonne , 2000 , Area Control / Area Influence , City Building

C:\Python>bgg.py 25417
BattleLore , 2006 , Campaign / Battle Card Driven , Fantasy

如果我能得到类似下面的内容,我想要的是:

C:\Python>bgg.py 822 25417
Carcassonne , 2000 , Area Control / Area Influence , City Building
BattleLore , 2006 , Campaign / Battle Card Driven , Fantasy

干杯

2 个答案:

答案 0 :(得分:1)

for gameid in argv[1:]:
    ...

[1:]表示没有第一个元素(脚本)的列表副本,它被称为切片。

答案 1 :(得分:1)

关键目标是重复需要多次执行操作的代码。为此,从argv列表中提取您的游戏ID(您似乎已经知道它是如何工作的)。现在,遍历每个ID并为每个ID执行操作,为原始代码中的ID执行操作。

from sys import argv
import requests
import xml.etree.ElementTree as ET

gameids = argv[1:]

for gameid in gameids: 
    game = requests.get("http://boardgamegeek.com/xmlapi/game/" + (gameid))
    r = game.text
    root = ET.fromstring(r)
    boardgame = root.findall('boardgame')
    for b in boardgame:
        name = b.find('name').text
        year = b.find('yearpublished').text
        mech = b.find('boardgamemechanic').text
        cat = b.find('boardgamecategory').text

        print (name, ",", year, ",", mech, ",", cat)

现在,使用python bgg.py 822 25417调用您的程序,您将看到您正在寻找的结果。