【问题标题】:I have an input that appends to a list, how do I print out the last list-item(the last input)?我有一个附加到列表的输入,如何打印最后一个列表项(最后一个输入)?
【发布时间】:2023-04-01 13:15:01
【问题描述】:

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

以下是相关代码:

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"

【问题讨论】:

标签: python list python-3.x append listitem


【解决方案1】:

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

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

【讨论】:

  • 很高兴它对你有用!如果您认为这是最好的答案,可以请mark it as accepted吗?谢谢!
【解决方案2】:

评论太长了:

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

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

或者看看OrderedSet 食谱。

【讨论】:

  • 不幸的是,我根本没有使用过 orderdict 或 orderset,但我会尝试看看我是否理解,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2021-07-03
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多