2013-08-01 34 views
1

我有一个列表是这样的:将列表分为子列表?

l = ['a,b,c,d' , 'a,b,c,d', 'a,b,c,d', 'a,b,c,d'] 

,我想让这个列表的格式如下:

l = [['a,b,c,d'],['a,b,c,d'],['a,b,c,d'],['a,b,c,d']] 

甚至四个单独的列表是好的,但我想基本上能够遍历每个子列表中的每个元素。这是我到目前为止:

for string in range(0, len(userlist)): 
    small_list = userlist[string:] 
    print(small_list) 

这不会将列表分离成我想要的列表。我在想,我有过打破名单成4

回答

4

块你可以做一个list comprehension

l = [s.split(",") for s in l] 
# result: [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']] 
2

你可以用它来获取字符的列表的列表:

l = [str.split(",") for str in l] 
# prints out [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']] 

或者这个,如果你不希望你的字符串分割成字符:

l = [[str] for str in l] 
# prints out [['a,b,c,d'], ['a,b,c,d'], ['a,b,c,d'], ['a,b,c,d']] 
0

尝试这个 -

result = [[each] for each in l] 
0
map(lambda x:[x], l) 

output: 
[['a,b,c,d'], ['a,b,c,d'], ['a,b,c,d'], ['a,b,c,d']]