在python (范例)中的一行中展平列表列表
Xajhqffl
・1 分钟阅读
有时你需要拼合列表的列表。旧的方法是使用一对循环在另一个循环中进行,尽管这样可以工作,但是,你可以不用这样做,这个技巧展示了如何使用列表推理来获取列表,并且将它展平为一行。
循环方法
#The list of lists
list_of_lists = [range(4), range(7)]
flattened_list = []
#flatten the lis
for x in list_of_lists:
for y in x:
flattened_list.append(y)
列表推理方式
#The list of lists
list_of_lists = [range(4), range(7)]
#flatten the lists
flattened_list = [y for x in list_of_lists for y in x]
这不是火箭科学,但是,它是更清晰的,而且我相信,比循环方法更快。