【问题标题】:I can't turn elements of my list into integers我无法将列表中的元素转换为整数
【发布时间】:2014-11-24 23:47:03
【问题描述】:

我的任务如下 1. 设计和编写模拟银行的程序。您的程序应该读取帐号、PIN、 并从文本文件开始余额。输入文件中的每一行文本都将包含所有信息 关于单个银行帐户 - 帐号、PIN 和期初余额。所有信息字段都是 用分号隔开。这是一些示例输入: 516;5555;20000 148;2222;10000 179;9898;4500 我的问题是我不知道如何将这些元素转换为我可以操作的整数,例如有人取钱,这是我目前所拥有的

def bank():
  myfile = pickAFile() 
  file = open(myfile)
  contents = file.readlines() 
  for i in range (0, len(contents)):
    items = contents[i].split(";")
  choice = requestInteger(" 1 - Withdraw, 2 - Deposit, 3 - Exit program ")
  if (choice == 1):
    PIN = requestInteger("Please enter your PIN")
    if (PIN == items[1]):
      print items[0]
    print("Invalid PIN")

我的 if 语句不起作用,因为 items 中的所有内容都是字符串而不是 int,语言是使用 python 语法但使用 java 库的 JES

【问题讨论】:

  • requestInteger的定义是什么?
  • requestInteger 提示用户输入整数

标签: python arrays string list int


【解决方案1】:

--- 新答案 --- 感谢您的反馈 - 您可以使用与列表理解相同的铸造技术。

items = [int(j) for j in contents[i].split(";")]

您也可以选择用 try/except 块包围它,具体取决于您对传入数据质量的信心。

--- 旧答案 --- 您可以在 requestInteger() 调用之后将其转换为整数:

...
choice = requestInteger(...)
try:
  choice = int(choice)
except ValueError:
  # Spit some error message back
if (choice == 1):
...

【讨论】:

  • 选择不是问题(抱歉,如果我让它看起来那样)问题是 PIN == items[1] 其中 items[1] 是一个字符串,当我需要它是一个整数时
  • 尝试搜索如何将字符串转换为整数
猜你喜欢
  • 1970-01-01
  • 2017-06-11
  • 2014-12-23
  • 1970-01-01
  • 2018-08-20
  • 2021-12-06
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
相关资源
最近更新 更多