python - 我有一个 append 到列表的输入,如何打印出最后一个列表项(最后一个输入)?

标签 python list python-3.x append listitem

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

相关代码如下:

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

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

下面是选择国家的功能:

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],但这只会打印出列表的第一项。由于我使用的循环,用户可以一遍又一遍地选择国家和城市,每次都会 append 到列表中。 我的问题是:如何在代码中打印出最后一个列表项( append 到列表的最后一项)
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/"+ countryList[0] + "/"+ cityList[0] + ".json"

最佳答案

使用 -1 作为列表的索引,即 countryList[-1] 将为您提供列表中的最后一项。

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

关于python - 我有一个 append 到列表的输入,如何打印出最后一个列表项(最后一个输入)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19980808/

相关文章:

python 字符串良好实践 : ' vs "

c++ - (C++) 使用节点/链表时得到不一致的结果。

windows - 如何在子进程中启动崩溃(很少)的应用程序

python - 特定格式 Python 的当前日期时间

python-3.x - wxPython TreeCtrl 非常慢,有数百万个节点(在多选树控件上)

python - 获取或创建匹配的 key 和用户 (Python - App Engine)

Python Queue.join()

python - Django Tastypie - 前置 URL 不起作用

r - 在 R 中合并两个列表

java - 如何在java中将字符串列表转换为列表对象?