1

我在打印列表中的项目时遇到问题。

以下是相关代码:

countryList = []

cityList = []

def startFunction():
     while True:
        print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
        menu = input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
        if menu == "1":
            countryFunction()
        elif menu == "2":
            cityFunction()
        elif menu == "3":
            forecastFunction()
        else: 
            print ("\nGoodbye")
            break

我首先有一个国家和城市的空列表,然后是一个带有循环的 startfunction,它将调用不同的函数。

选择国家/地区的功能如下所示:

def countryFunction():
    countryc = input("Enter which country your city is in(in english): ")
    countryList.append(countryc)

然后打印函数如下所示:

def forecastFunction():
    r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countryList[0] + "/" + cityList[0] + ".json")
    data = r.json()
    #Above is the problem, countryList[0] and cityList[0]  

正如你现在看到的那样,我刚刚放了countryList[0]但这只会打印出列表的第一项。而且由于我使用的循环,用户可以一遍又一遍地选择国家和城市,每次都会附加到列表中。我的问题是:如何打印代码中的最后一个列表项(附加到列表的最后一项)
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countryList[0] + "/" + cityList[0] + ".json"

4

2 回答 2

3

用作-1列表的索引,即countryList[-1]会给您列表中的最后一项。

尽管本教程显示了一个字符串索引示例,但它对列表的工作方式相同:http: //docs.python.org/2/tutorial/introduction.html#strings

于 2013-11-14T14:54:39.603 回答
2

评论太长了:

正如另一个答案指出的那样,您只需要使用-1索引功能,如countryList[-1].

但是,您似乎也想使用类似有序集合的数据结构,以避免存储来自用户的重复条目。在这种情况下,使用OrderedDict可能更适合您。

或者看看OrderedSet配方。

于 2013-11-14T14:59:34.303 回答