[英]How do I access the 1st element of each list in a lists of lists
Example: 例:
numbers = ['1','2','3']
letters = ['a','b','c']
I want to get [1,a] as a results. 我想得到[1,a]作为结果。 Yeah I can loop through it, but I'm wondering if there is a fast one line way of doing this.
是的,我可以遍历整个过程,但是我想知道是否有一种快速的单行方法来做到这一点。
EDIT EDIT !!!! 编辑编辑!!!!
I made a horrible mistake in describing the problem. 我在描述问题时犯了一个可怕的错误。
I have access to the combined list (the list of lists of the question): 我可以访问组合列表(问题列表):
list_of_lists = [ numbers, letters]
which is equal to: 等于:
[ ['1','2','3'],['a','b','c']]
Sorry for the confusion. 对困惑感到抱歉。 The end result is still the same, this would be ['1','a'].
最终结果仍然相同,这将是['1','a']。
Try a list comprehension : 尝试列表理解 :
# (numbers, letters) can be replaced with `list_of_lists`
>>> [ x[0] for x in (numbers, letters) ]
['1', 'a']
import operator
map(operator.itemgetter(0), [numbers, letters])
list_of_lists = [['1', '2', '3'], ['a', 'b', 'c']]
list_of_firsts = [l[0] for l in list_of_lists]
您可能正在寻找拉链
我会尝试:
zip(*list_of_lists)[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.