简体   繁体   中英

Divide list and append the list to separate lists python

I have a list that is to be divided into two parts then, each part have to be written into different lists. The code which i tried is here and it works fine.

import sys
a = ['name','2',3,4,5,'a','b','c','d',10,4,'lol','3']
print len(a)
list1 =[]
list2 = []
for i in xrange(0, (len(a)/2)):
    list1.append(a[i])
    list2.append(a[(i)+((len(a)/2))])
list2.append(a[(len(a))-1])
print list1
print list2

I would like to know if there is any other better alternative way to do this..

Use Python slice notation :

a = ['name', '2', 3, 4, 5, 'a', 'b', 'c', 'd', 10, 4, 'lol', '3']
n = len(a)
print(n)
mid = n // 2
list1, list2 = a[:mid], a[mid:]
print(list1)
print(list2)
a = ['name','2',3,4,5,'a','b','c','d',10,4,'lol','3']
mid = len(a)//2
list1, list2=a[:mid], a[mid:]


>>> list1
['name', '2', 3, 4, 5, 'a']
>>> list2
['b', 'c', 'd', 10, 4, 'lol', '3']

quite similar to answer 1, but a bit shorter and a bit faster

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM