我试图在python中创建一个列表列表:
[[0, 1, 2], [4, 5, 6], [8, 9, 10], [11, 12]]
但我的功能并未附加最后一个列表([11,12])
a = [a for a in list(range(13))]
print(a)
final_list = []
b =[]
for num in a:
if len(b) <3:
b.append(num)
else:
b = []
if len(b) == 3:
final_list.append(b)
print(final_list)
[[0, 1, 2], [4, 5, 6], [8, 9, 10]]
答案 0 :(得分:2)
# You don't need `a` to be a list here, just iterate the `range` object
for num in range(13):
if len(b) < 3:
b.append(num)
else:
# Add `b` to `final_list` here itself, so that you don't have
# to check if `b` has 3 elements in it, later in the loop.
final_list.append(b)
# Since `b` already has 3 elements, create a new list with one element
b = [num]
# `b` might have few elements but not exactly 3. So, add it if it is not empty
if len(b) != 0:
final_list.append(b)
另外,请检查此classic question以了解有关将列表拆分为大小均匀的块的更多信息。
答案 1 :(得分:1)
在print(final_list)
之前,添加以下行:
if len(b):
final_list.append(b)
这将包含仅包含2个元素的列表。