python- a list into multiple smaller lists

python is a list of the more common data types, it is an iterable, what iteration? It can be understood as a simple: for a target loop can be traversed

Today, to get a list like this

list_info = ['name zhangsan','age 10','sex man','name lisi','age 11','sex women']

 

In fact, it means two people's personal information, the fields are the same, but in a common list, no way to distinguish between, first need to be this big list is divided into two (this is not necessarily the number of people, each sub-list is a list of fixed length) small list

def list_of_groups(list_info, per_list_len):
    '''
    :param list_info:   列表
    :param per_list_len:  每个小列表的长度
    :return:
    '''
    list_of_group = zip(*(iter(list_info),) *per_list_len) 
    end_list = [list(i) for i in list_of_group] # i is a tuple
    count = len(list_info) % per_list_len
    end_list.append(list_info[-count:]) if count !=0 else end_list
    return end_list

if __name__ == '__main__':
    list_info = ['name zhangsan', 'age 10', 'sex man', 'name lisi', 'age 11', 'sex women']
    ret = list_of_groups(list_info,3)
    print(ret)

 

The above is the result of this function is performed, the success of a large list of irregular treatment done according to certain rules, you can also convert the above list to a small dictionary, more intuitive way to get the data by key-value pairs

    list_dict = []
    for item in ret:
        data = {}
        data['name'] = item[0].split(' ')[1]
        data['age'] = item[1].split(' ')[1]
        data['sex'] = item[2].split(' ')[1]
        list_dict.append(data)
    print(list_dict)

 

 

Two kinds of more visual approach, freely choose it

Guess you like

Origin www.cnblogs.com/lutt/p/12037454.html