Python 如何生成返回数字位置值的函数?

Python 如何生成返回数字位置值的函数?,python,python-3.x,function,math,numbers,Python,Python 3.x,Function,Math,Numbers,我需要创建一个函数,返回与其位置值对应的值 例如: 位置值 1234中的10返回3 1234中的百返回2 一千、二百、三百一十、四个单位 我试过这个: def位置_值(x): x=str(x) 数字=[] 数字。扩展(x) 数字。反向() 对于索引,i在枚举中(数字): 如果索引==0: 打印(i)#所以x是1234,这里我可以得到4。 通过我的尝试,我可以通过索引得到这些数字。我认为使用带有位置值名称的列表(unit、ten、一百、unit of 1000等)将有助于描述函数的每个查询 输出

我需要创建一个函数,返回与其位置值对应的值

例如:

位置值
1234中的10返回3
1234中的百返回2
一千、二百、三百一十、四个单位

我试过这个:

def位置_值(x):
x=str(x)
数字=[]
数字。扩展(x)
数字。反向()
对于索引,i在枚举中(数字):
如果索引==0:
打印(i)#所以x是1234,这里我可以得到4。
通过我的尝试,我可以通过索引得到这些数字。我认为使用带有位置值名称的列表(unit、ten、一百、unit of 1000等)将有助于描述函数的每个查询

输出示例:打印函数时:

1千分之一
200
310
4单元
#当这个数字更大的时候,它还会继续

如果需要数字,可以使用以下方法:

def positional_value(x):
  numbers=[]
  v = x
  while v != 0:
    numbers.append(v%10)
    print(v%10)
    v = v // 10
    print(v)
  return numbers
但如果您想在大数字中使用特定数字的索引:

def positional_value(x, n):
  numbers=str(x)
  return numbers.find(str(n)) 

print(positional_value(1234, 2))
1
print(positional_value(1234, 4))
3
但如果你想向后看,倒过来也行

def positional_value(x, n):
  numbers=str(x)[::-1]
  return numbers.find(str(n)) 

print(positional_value(1234, 2))
2
print(positional_value(1234, 4))
0

与接受的答案类似,但将值用作字符串,而不是整数除法

def positional_values(x):
    positions = ['unit', 'ten', 'hundred', 'unit of thousand', 'ten-thousand',
                 'hundred-thousand', 'unit of million', ]
    for i, c in enumerate(str(x)):
        print(f"{int(c)}: {positions[len(str(x)) - i - 1]}")

positional_values(1234)

1: unit of thousand
2: hundred
3: ten
4: unit

您能否添加一个示例,说明在传递函数时希望该函数打印什么内容
1234
?如果您希望一个
函数返回与其位置值相对应的值
,则似乎
位置值
应该包含两个参数:数字和位置。是否要将数字转换为单词?^(添加了一个简单的查找表,从字符串
'hundereds'、“数千”
等到相应的数字索引)@Deepstop示例!这将有助于将相应的单词添加到
打印(位置值(1234,1))
编辑为一个更完整的示例。显然,您需要知道支持的最大值,以便扩展它以包含这些单词。此外,添加错误类型、负数等的健全性检查。这是一个干净的代码,只需要在函数中,并且是完美的!好的,更新为函数。
def positional_values(x):
    positions = ['unit', 'ten', 'hundred', 'unit of thousand', 'ten-thousand',
                 'hundred-thousand', 'unit of million', ]
    for i, c in enumerate(str(x)):
        print(f"{int(c)}: {positions[len(str(x)) - i - 1]}")

positional_values(1234)

1: unit of thousand
2: hundred
3: ten
4: unit