[英]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 : 使用Python切片表示法 :
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 与答案1非常相似,但更短,更快一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.