简体   繁体   English

如何访问列表列表中每个列表的第一个元素

[英]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.

相关问题 如何对列表列表进行排序并按间隔仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements by intervals? 如何对列表列表进行排序并仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements? 从列表列表中删除第一个元素,然后是第一个和第二个元素[保留] - Removing the 1st element then 1st and 2nd element from a list of lists [on hold] 比较列表列表中的第一个元素并写入重复值的数量 - Compare 1st element in list of lists and write number of repeated values 如何在列表列表中的每个列表中添加元素? - How do I add an element to each list in a list of lists? 将列表列表的第一个元素与另一个列表进行比较,然后仅添加与新列表匹配的列表 - Comparing the 1st element of list of lists to another list then adding only the lists that match to a new list 如何将单独列的第一行附加到列表列表中 - How to append the 1st row of separate columns to a list of lists Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series Python:如何遍历两个列表中的每个值,计算在第一个列表中值&lt;22或在第二个列表中&lt;27的出现次数? - Python: How to iterate through each value in two lists, count the occurrences that value is < 22 in the 1st list OR < 27 in the 2nd list? 如何将列表列表中与第一个列表中的单词匹配的单词替换为与第二个列表中的第一个单词具有相同位置的单词? - How can I replace a word in my list of lists that matches a word from 1st list into a word that has the same position as the 1st one in the 2nd list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM