初学者Python:将列表提取为整数

时间:2013-10-05 17:00:14

标签: python list formatting extract

我是初学程序员,我需要帮助从列表中提取数字并将它们转换回整数。程序采用数字输入(如305.67)并拆分为305和67.附加的是显示未完成部分的代码。任何帮助表示赞赏,谢谢!

def getDollarFormatText(dolAndCent):

    separateDolCent = str(dolAndCent).rsplit('.',1)

    return separateDolCent

2 个答案:

答案 0 :(得分:3)

你真是太近了!

def getDollarFormatText(dolAndCent):

    separateDolCent = [int(x) for x in str(dolAndCent).split('.')]

    return separateDolCent

我在[int(x)for dol in dolAndCent.split('。')]中所做的是list comprehension(列表推导是非常 python中常见的习惯用法,一旦你熟悉它们就非常强大)。从本质上讲,它会将你的字符串拆分为'。' (正如你之前所做的那样),然后创建一个小循环来遍历每个元素('。'之前和之后的部分)。对于其中的每一个,它都会转换为int的整数。功能

我将rsplit更改为split,因为您拆分的字符串的哪一边并不重要,我删除了1,因为只有一个&#39 ;'反正。


作为旁注,没有理由创建separateDolCent变量:

def get_dollar_format_text(dol_and_cent):
    '''Returns the dollar and cents part of a money amount as
    a two element list of integers, where the first element is
    dollars and the second is cents.
    '''
    return [int(x) for x in str(dol_and_cent).split('.')]

注意我是如何将变量从camelCase更改为using_underscores的。对于函数和变量名,这是python社区中的首选。我还使用docstring为您的函数添加了一些文档。


如果您需要处理23.4345.4311等数字,可以对代码进行以下编辑:

def get_dollar_format_text(dol_and_cent):
    '''Returns the dollar and cents part of a money amount as
    a two element list of integers, where the first element is
    dollars and the second is cents.
    '''
    return [int(x) for x in '{0:.2f}'.format(dol_and_cent).split('.')]

这样做会强制使用两位小数格式化数字,以便2变为2.003.4变为3.40,{{1} }成为345.4311。这样,你总是获得两位小数的分数。

答案 1 :(得分:2)

你快到了:

def getDollarFormatText(dolAndCent):

    separateDolCent = map(int,str(dolAndCent).rsplit('.',1))

    return separateDolCent
  

如何将每个整数保存到新变量中?

只需将它们提取为两个变量(例如ab):

def getDollarFormatText(dolAndCent):

        a,b = map(int,str(dolAndCent).rsplit('.',1))

        print a
        print b

getDollarFormatText("5.70")

这将打印:

5
70
相关问题