【问题标题】:Python : How to get the respective age and balance of the matching name?Python:如何获取匹配名称的相应年龄和余额?
【发布时间】:2020-05-04 04:34:54
【问题描述】:

目标仅使用 python 基础列表、while 循环、if else 的迷你银行模拟。

问题 2. 搜索帐户。 注意我希望我的程序返回匹配名称的相应年龄和余额。提前致谢。

print("""1. Add Account
2. Search Account"
3. Exit \n\n""")

name = []
age = []
balance = []

while True:

    choice = input("What is your choice ? : ")

    if choice == "1":

        name.append(input("Name : "))

        age.append(input("Age : "))

        balance.append(input("Balance : "))

        print("Account Registration Done\n\n")

    if choice == "2":

        y = input("What is your Account Name ? > : ") 

        if y in name:  # i want my program to return the respective age and balance of the matching name.
            print(name[0]) # Here is the issue and i don't know how to fix.Please Kindly enlighten me
            print(age[0])
            print(balance[0])

        else:
            print(
                f"Your name[{y}] have't registered yet.Please register first")

    if choice == "3":
        break

【问题讨论】:

  • 我希望我的程序返回新添加的帐户” 是不是一直想要新添加的帐户详细信息或与名称匹配的帐户详细信息?
  • 与名称匹配的帐户的详细信息。非常感谢您的评论。
  • 您是否可以更新问题以使其清楚?我们已经有了两个答案。

标签: python-3.x list indexing


【解决方案1】:

您的代码中最近添加的银行帐户将是列表末尾的银行帐户。您可以通过name[-1]age[-1]balance[-1] 访问它。 Python 中的负索引意味着向后搜索,因此 -1 为您提供列表的最后一个元素。

要搜索您可以执行的帐户:

if y in name:
    found = name.index(y)

然后你可以通过age[found]balance[found] 得到各自的年龄和平衡。

【讨论】:

  • 谢谢谢谢*1000000000000000000000000000000。现在我的问题解决了。非常感谢。谢谢。你的回答很有帮助。
【解决方案2】:

如果您要在列表末尾添加新元素(即.appending() 它们),您可以list[-1] 获取列表中的最后一个(因此是最新的)元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 2018-07-23
    • 2010-10-19
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多