【问题标题】:REALLY simple functions with tuples (python)非常简单的元组函数(python)
【发布时间】:2016-10-16 16:24:44
【问题描述】:

我知道这很容易,但我根本不懂如何编码。所以我需要创建两个函数(如果你只能帮我一个就好了):

函数 a 接收一个正整数并将其转换为一个元组,如下所示:

>>>a(34500)
(3, 4, 5, 0, 0)
>>>a(3.5)
ValueError: a: error

函数 b 接收元组并将其转换为整数,如下所示:

>>>b((3, 4, 0, 0, 4))
34004
>>>b((2, ’a’, 5))
ValueError: b: error

我还没有学到很多东西,只有函数,while 和 for 循环,元组,raise 和 isinstance(对于错误消息?),可能还有其他一些东西。我试过寻找答案,但他们都用了我没学过的东西。

【问题讨论】:

  • 转为字符串再转为整数
  • 我们需要查看函数b的代码来帮助您。现在看起来它只接受整数,而您正在尝试输入一个导致错误的字符串。
  • @Whud 这两个函数都不存在。 OP 希望我们为他写。
  • 你是说那些 ValueError 是你想要的,还是你现在得到的并且你想避免它们?
  • '他们都使用了我没学过的东西' - 这是一个问题,因为这是一个家庭作业吗?否则,你不想学点新东西吗?

标签: python function tuples


【解决方案1】:
def to_tuple(input_number):
    # check if input number is int or not
    if isinstance(input_number,(int)):
        # convert number to string
        to_string = str(input_number)
        # finally convert string to
        # list of numbers followed by converting the list to tuple
        tuple_output = tuple(map(int,to_string))
        return tuple_output
    # if not int return empty tuple
    # well coz nobody likes useful but ugly python tracebacks
    else:
        return ()

# lets see example
number = 3450
print to_tuple(number)
(3, 4, 5, 0)

number = 353984
print to_tuple(number)
(3, 5, 3, 9, 8, 4)

number = 2.6
print to_tuple(number)
()

如果你喜欢这个例子,我会发布第二部分的答案

【讨论】:

  • 感谢您的帮助。我知道它很旧,正是我想要的。
【解决方案2】:

试试这个

def a(n):
result = []

while n > 0:
    result.append(n%10)
    n=n//10

return tuple(reversed(result))

对于问题 2,尝试反过来做同样的事情,即将每个数字乘以 1、10、100 并将它们相加。

也不要忘记错误检查代码。

【讨论】:

    【解决方案3】:

    cmets 已经说明了您可以做什么: 通过执行将 int 转换为 str (我知道这不适用于浮点数,在这里你可以展示一些进一步的努力:))

    for c in str(integerVariable):
        print c
    

    反之则更简单。

    ''.join(tupleVariable)
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多