附加一个空列表但转换为NoneType

时间:2012-01-24 17:16:49

标签: python list

在以下代码中:

all_subsets = []
subsets = [[], [2]]
left_most = 1 
for subset in subsets:
    print subset
    all_subsets.append(subset)
    all_subsets.append(subset.append(left_most))
print all_subsets

我认为返回应该是[[], [1], [2], [2, 1]],但实际上我得到了[[1], None, [2, 1], None]的回报。即,[]已转换为None

我认为这是在循环中修改subset两次的问题,它指向相同的物理地址。但是,即使我在修改列表之前制作了本地副本,也无法解决问题,例如:

all_subsets = []
subsets = [[], [2]]
left_most = 1
for subset in subsets:
    print subset
    subset_orig = list(subset)
    subset_plus = list(subset).append(left_most)
    all_subsets.append(subset_orig)
    all_subsets.append(subset_plus)
print all_subsets

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:5)

list.append()始终返回None,所以

all_subsets.append(subset.append(left_most))

None追加到all_subsets。你可能只是想要

subset.append(left_most)

因为您已将subset附加到之前的行中的all_subsets

答案 1 :(得分:5)

问题在于append()就地修改了列表,并返回None

以下是修复代码的一种方法:

all_subsets = []
subsets = [[], [2]]
left_most = 1 
for subset in subsets:
    print subset
    all_subsets.append(subset)
    all_subsets.append(subset + [left_most])
print all_subsets

这会产生您所期望的[[], [1], [2], [2, 1]]