我试图在奇数和偶数之间分割我的列表。到目前为止,我的代码是:
odds = []
evens = []
new_list = [1, 4, 2, 6, 5, 3, 7]
for index in new_list:
if index % 2 == 0:
evens += [index]
else:
odds += [index]
但是,当我打印evens列表时,它会导致无。我已单独打印数字,如:
for index in new_list:
if index % 2 == 0:
evens += [index]
print(index)
打印偶数。为什么他们不会添加到evens列表?
奇数加入列表没有问题。
编辑:
完整的功能是:
def evens_at_end(list1):
odds = []
evens = []
list2 = [3,4,5,9]
for index in list1:
if index % 2 == 0:
evens += [index]
else:
odds += [index]
new_list = list2 + evens
return new_list
list1为[1,4,2,6,5,3,7]
答案 0 :(得分:1)
使用列表推导
evens = [x for x in list1 if x % 2 == 0]
odds = [x for x in list1 if x not in evens]