【问题标题】:Taking user input into dataset, then check items in dataset and move to new dataset将用户输入输入数据集,然后检查数据集中的项目并移动到新数据集
【发布时间】:2022-11-02 03:27:05
【问题描述】:

我想获得用户对 ISBN-10/ISBN-13 的输入,并能够在将每个输入放入数据集后检查其长度,然后将 ISBN-13 转换为 ISBN-10。最后应该是 ISBN-10 的列表。当我尝试并且不知道我的代码哪里出错时,我目前得到一个空列表。

import pyisbn

alist = []
def get_dataset():
    while True:
        try:
          dataset = [str(_) for _ in input("\nEnter Book ID(s): ").replace(',', ' ').split()]
        except ValueError:
          print("\nInvalid Input")
          continue
          
          for _ in range(0, len(dataset)):
            if len(_) == 10:
              alist.append(dataset)
            if len(_.replace('-', '')) == 13:
              alist.append(pyisbn.convert(dataset))
            
        if len(dataset) < 1:
          print("\nPlease enter at least 1 Book ID.")
        else:
          return alist

print(get_dataset())

我在检查数据集长度后尝试移动 for 循环,但代码在输入后才结束。我也尝试将代码放在 try 循环之外,但随后得到 Object of type 'int' has no len 错误。最后,我尝试从函数中删除所有内容,但这似乎并没有改变我得到的任何错误。

【问题讨论】:

  • 如果您不打算使用它,通常只使用下划线作为变量名。它通常用于一次性值。

标签: python


【解决方案1】:

我认为你的 for 循环是问题所在。尝试这个:

import pyisbn

alist = []
def get_dataset():
    while True:
        try:
          dataset = [str(_) for _ in input("
Enter Book ID(s): ").replace(',', ' ').split()]
        except ValueError:
          print("
Invalid Input")
          continue
          
        for id_value in dataset:
          if len(id_value) == 10:
            alist.append(id_value)
          if len(id_value.replace('-', '')) == 13:
            alist.append(pyisbn.convert(id_value))
            
        if len(dataset) < 1:
          print("
Please enter at least 1 Book ID.")
        else:
          return alist

print(get_dataset())

【讨论】:

    猜你喜欢
    • 2015-08-02
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多