如何在Python中创建多维列表? [英] How can i create multidimensional list in Python?
本文介绍了如何在Python中创建多维列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据某些条件遍历一维列表时创建多维列表.
How can i create a multidimensional list while iterating through a 1d list based upon some condition.
我正在遍历一维列表,每当找到一个'\ n'时,都应该在创建的列表后附加一个新列表,例如,
I am iterating over a 1d list and whenever i find a '\n' i should append the so created list with a new list, for example,
a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]
所以我希望它像这样
new_list = [[1,2,3,4],[6,7,8,9,0],[3,45,6,7,2]]
我应该怎么做?请帮助
def storeData(k):
global dataList
dlist = []
for y in k:
if y != '\n':
dlist.append(y)
else:
break
return dlist
这是我尝试过的.
推荐答案
使用 itertools.groupby
即可完成工作(按 not 作为换行进行分组):>
Using itertools.groupby
would do the job (grouping by not being a linefeed):
import itertools
a = [1,2,3,4,5,'\n',6,7,8,9,0,'\n',3,45,6,7,2]
new_list = [list(x) for k,x in itertools.groupby(a,key=lambda x : x!='\n') if k]
print(new_list)
我们比较关键真值以过滤出 \ n
We compare the key truth value to filter out the occurrences of \n
结果:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [3, 45, 6, 7, 2]]
这篇关于如何在Python中创建多维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文