读取Python中可变长度的数组字符串

2024-09-28 23:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读一个数组,数组中的列有不同的长度。例如,请参考下面的列表。在

binary,none1,Param,none2

77,2601,54,55

70,,25,224

71,,33,38

67,,22,40

0,,14,

0,,47,

0,,21,

0,,88,

0,,50,

0,,17,

0,,11,

0,,26,

(请将逗号替换为空格以获取列表)

我想将其导入python并为空集插入“null”。我试着把它转换成一个对称的数组。感谢任何帮助。在


Tags: 列表param数组null空格逗号binary空集
2条回答
fileName = raw_input ()
try:
    file = open (fileName)
    input = file.read ()
    file.close ()
except: # Test case
    input = '''77 2601 54 55
    70  25 224
    71  33 38
    67  22 40
    0  14 
    0  47 
    0  21 
    0  88 
    0  50 
    0  17 
    0  11 
    0  26 '''

array = [
    [
        (element if element else None)
        for element in line.split (' ')
    ]
    for line in input.split ('\n')
]

for row in array:
    print row

如前所述,None是Python中null的等价物。您可以通过以下方法实现:

# Keep column headers. Convert numbers to numbers. Empty strings into None (empty "set")

def get_col(col):
    if col:
        try:
            return int(col)
        except:
            return col
    else:
        return None


rows = [row.split (',') for row in data.split ('\n')]
# Convert empty columns into None and
rows = [[get_col(col) for col in cols] for cols in rows]

这将导致rows如下所示:

^{pr2}$

替换get_col函数如下:

def get_col(col):
    if col:
        return col
    else:
        return 'null'

将使您rows如下所示:

[['binary', 'none1', 'Param', 'none2'], ['77', '2601', '54', '55'], ['70', 'null', '25', '224'], ['71', 'null', '33', '38'],   etc...

(使用Python 2.7.9)

相关问题 更多 >