0
我想在奇数和偶数之间分割我的列表。到目前为止,我的代码是:列表元素将不会添加到新列表(Python)
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]
然而,当我打印唇上列出它导致无。我已经单独打印了数字,如下所示:
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]
对我来说工作正常,除了'else'行被错误地缩进。 – Selcuk
哦,我没有注意到。谢谢你告诉我:) –
你打印的名单如何?如果我在你的代码后添加'print evens',它就可以工作。你把这些代码放在一个函数中,可能忘记返回'evens'? –