将混合列表转换为python中的浮点数

时间:2016-11-29 16:37:53

标签: python int

我正在尝试编写一个函数来删除非浮点数并将所有int转换为浮点数。我在自己的调试过程中包含了一些打印语句。我想要将“.0”添加到int以返回列表的转换。

std_in= ['1', '2', '2.1', 'ab1', '1ab']

结果     ['1','2','2.1']     

期望的结果     ['1','2','2.1']          ['1','2','2.1']

def float_sort(std_in):
    float_sort = std_in
    sorted_float = ""
    float_sort = " ".join(float_sort)
    float_sort=re.findall(r"\b(^[+-]d+\e+\d+|\-\d+\.\d+|\-d+|\d+\.\d+|\d+)\b", float_sort)
    print(float_sort)
    [float(i) for i in float_sort]
    sorted_float = sorted(float_sort, key=len)
    print(type(sorted_float))
    sorted_float = " ".join(sorted_float)
    print(sorted_float)
    sorted_float = sorted_float.split()

4 个答案:

答案 0 :(得分:4)

请尝试以下代码:

res = []
std_in = ['1', '2', '2.1', 'ab1', '1ab']

for i in std_in:
    try:
        res.append(float(i))
    except ValueError:
        pass

<强>输出:

>>> res
[1.0, 2.0, 2.1]

答案 1 :(得分:2)

ettananyPatrick Haugh提供的答案都很好,但只是为了好玩,我的回答是:

l = ['1', '2', '2.1', 'ab1', '1ab']

def float_generator(mylist):
    for n in mylist:
        try:
            yield float(n)
        except ValueError:
            pass

print list(float_generator(l))

答案 2 :(得分:2)

您可以使用解析器功能的方法,只应解析数据。

def parsefloat(str):
    try:
        return float(str)
    except ValueError:
        return False

然后,对列表中的每个项目应用parsefloart

res = filter(lambda x: x, map(parsefloat, std_in))

答案 3 :(得分:1)

如果您希望输出为字符串:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadConnect4 {

    private static final String TEST_BOARD = "-------\n"
            + "-------\n"
            + "-------\n"
            + "-------\n"
            + "-Y-----\n"
            + "-Y--R--\n";

    private static final int ROWS = 6;
    private static final int COLS = 7;

    public static void main(String[] args) throws Exception {
        ByteArrayInputStream pretendFile = new ByteArrayInputStream(TEST_BOARD.getBytes());
        char[][] board = readBoard(pretendFile);
        printBoard(board);
    }

    private static void printBoard(char[][] board) {
        for(int k = 0; k < board.length; k++) {
            for(int j = 0; j < board[k].length; j++) {
                System.out.print(board[k][j]);
            }

            System.out.println();
        }
    }

    private static char[][] readBoard(InputStream stream) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line;
        int row = 0;
        char[][] result = new char[ROWS][COLS];

        // Read each line, stop when end of file (line is null)...
        while((line = reader.readLine()) != null) {
            // For each column...
            for(int col = 0; col < 7; col++) {
                // Get character from line, store in array
                result[row][col] = line.charAt(col);
            }
            row++;
        }
        return result;
    }
}