2017-06-18 133 views
2
fp.readline() 
for line in fp: 
    line_lst = line.strip().split(',') 

想我得到了一堆名单中运行上面的代码后:如何从列表中创建列表?

['a','b','c']['1','2','3']['A','B','C'] 

我怎么能得到另一个列表

['a','1','A']['b','2','B']['c','3','C'] 

从列表,而不是直接创造的呢?

+0

您是否总是希望第一个元素位于名单? – Arc676

+0

@ Arc676其实我想知道如何将列表转换为['a','1','A'] ['b','2','B'] ['c','3',' C'] – Chrisiicandy

+0

你应该在你的文章中包含这类信息。你可以[编辑]这样做。 – Arc676

回答

2

假设所有列表有相同数量的元素

my_lists = [my_list_1, my_list2, ...] 
for i in xrange(len(my_lists[0])): 
    print [l[i] for l in my_lists] 

一个例子的...

>>> my_lists = [['a','b','c'],['1','2','3'],['A','B','C']] 
>>> for i in xrange(len(my_lists[0])): 
...  print [l[i] for l in my_lists] 
... 
['a', '1', 'A'] 
['b', '2', 'B'] 
['c', '3', 'C'] 
+0

相关文档:https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions – Arc676

+0

@Chrisiicandy如果您的问题得到解决,或者接近您的问题,您可以接受/ upvote答案一个决议。从[这里](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),“接受答案是重要的,因为它既奖励海报解决你的问题,并告知其他人你的问题解决了。“ –

+0

@DebosmitRay kk – Chrisiicandy

2

你可以使用

all_list = [['a','b','c'],['1','2','3'],['A','B','C']] 
result = [x[0] for x in all_list] 
print(result) 

这就是所谓的列表理解在Python。

为了您的需要,您应该使用zip函数在这里,link由@ Arc676给出。

all_list = [['a','b','c'],['1','2','3'],['A','B','C']] 
# result = list(zip(all_list[0], all_list[1], all_list[2])) 
# if you have more list in all_list, you could use this 
result = list(zip(*all_list)) 
print(result) 
+0

相关文档:https://docs.python.org/2/library/functions.html#zip – Arc676

+0

all_list = [['a','b','c'] ['1','2', '3'] [ 'A', 'B', 'C']]'?这不会编译。 –

+0

@DebosmitRay对不起,您应该在我的手机中添加逗号,我忘了添加它。 – danche

0

你可以尝试下面的东西。

var aggregateList = line_lst.map(function (value) { return value[0]; }); 

编辑:哎呀,我还以为是在JavaScript部分,为蟒蛇:

aggregateList = map(lambda value: value[0], line_lst) 
0

这应该这样做...但它真的只是从每个列表中获得第一项的,所以我不敢肯定,如果这是你想要

new_list = [] 
for sub_list in line_lst: 
    new_list.append(sub_list[0]) 

你也可以做到这一点(我更喜欢)

什么210
0

刚:

zip(['a','b','c'], ['1','2','3'], ['A','B','C']) 

其中给出:

[ ('一个', ' ('''','B'),('c','3','C')]