在Python

时间:2015-06-29 08:42:29

标签: python arrays

我想读取数组中列的长度不同的数组。例如,请参阅下面的列表。

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”。我试图将其转换为对称数组。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如前所述,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看起来如下:

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

更换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)