如何将列表转换为字节?

时间:2019-04-21 15:20:30

标签: python python-3.x numpy

我有一个float列表,我想将其转换为字节。能否请一些帮助我做到这一点。 例如

import datetime

validity = ['2712/2812','2723/2805','2800/2812','3012/0112','3023/0105','0110/0112']

def get_valid_hours(valid):

    hours_li = []
    #Parse the start date and end date as datetime
    start_date_str, end_date_str = valid.split('/')
    start_date = datetime.datetime.strptime(start_date_str,'%d%H')
    end_date = datetime.datetime.strptime(end_date_str, '%d%H')

    #If start date less than equal to end date
    if start_date <= end_date:
        dt = start_date
        i=0
        #Keep creating new dates until we hit end date
        while dt < end_date:
            #Append the dates to a list
            dt = start_date+datetime.timedelta(hours=i)
            hours_li.append(dt.strftime('%d%H'))
            i+=1
    #Else split the validity into two and calculate them separately
    else:
        start_date_str, end_date_str = valid.split('/')
        return get_valid_hours('{}/3023'.format(start_date_str)) + get_valid_hours('0100/{}'.format(end_date_str))

    #Append sublist to a bigger list
    return hours_li

for valid in validity:
    print(get_valid_hours(valid))

我想要类似的东西

['2712', '2713', '2714', '2715', '2716', '2717', '2718', '2719', '2720', '2721', '2722', '2723', '2800', '2801', '2802', '2803', '2804', '2805', '2806', '2807', '2808', '2809', '2810', '2811', '2812']
['2723', '2800', '2801', '2802', '2803', '2804', '2805']
['2800', '2801', '2802', '2803', '2804', '2805', '2806', '2807', '2808', '2809', '2810', '2811', '2812']
['3012', '3013', '3014', '3015', '3016', '3017', '3018', '3019', '3020', '3021', '3022', '3023', '0100', '0101', '0102', '0103', '0104', '0105', '0106', '0107', '0108', '0109', '0110', '0111', '0112']
['0100', '0101', '0102', '0103', '0104', '0105']
['0110', '0111', '0112']

2 个答案:

答案 0 :(得分:2)

由于您已对此标签numpy进行了标记,因此简称为tobytes

a = np.array(l)
a.tobytes()

b'\x9a\x99\x99\x99\x99\x99\xb9?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00@\xcd\xcc\xcc\xcc\xcc\xcc\x08@ffffff\x10@'

此结果可以使用frombuffer作为ndarray重新处理,但是将不保留原始形状。

答案 1 :(得分:0)

希望这是您想要的:

$builder
        ->add('categorie', EntityType::class, [
        // This field shows all the categories
        'class'    => Categorie::class,
        'placeholder' => 'Select choice',
        'mapped' => false,
        'multiple' => true,
        'required' => false,
        'attr' => [
            'class' => 'mdb-select',
            'placeholder' => 'test',
         ]
        ])