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']
从列表,而不是直接创造的呢?
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']
从列表,而不是直接创造的呢?
假设所有列表有相同数量的元素
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']
相关文档:https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions – Arc676
@Chrisiicandy如果您的问题得到解决,或者接近您的问题,您可以接受/ upvote答案一个决议。从[这里](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),“接受答案是重要的,因为它既奖励海报解决你的问题,并告知其他人你的问题解决了。“ –
@DebosmitRay kk – Chrisiicandy
你可以使用
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)
你可以尝试下面的东西。
var aggregateList = line_lst.map(function (value) { return value[0]; });
编辑:哎呀,我还以为是在JavaScript部分,为蟒蛇:
aggregateList = map(lambda value: value[0], line_lst)
这应该这样做...但它真的只是从每个列表中获得第一项的,所以我不敢肯定,如果这是你想要
new_list = []
for sub_list in line_lst:
new_list.append(sub_list[0])
你也可以做到这一点(我更喜欢)
什么210刚:
zip(['a','b','c'], ['1','2','3'], ['A','B','C'])
其中给出:
[ ('一个', ' ('''','B'),('c','3','C')]
您是否总是希望第一个元素位于名单? – Arc676
@ Arc676其实我想知道如何将列表转换为['a','1','A'] ['b','2','B'] ['c','3',' C'] – Chrisiicandy
你应该在你的文章中包含这类信息。你可以[编辑]这样做。 – Arc676