Python 提取每个子列表的第一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25050311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract first item of each sublist
提问by konrad
I am wondering what is the best way to extract the first item of each sublist in a list of lists and append it to a new list. So if I have:
我想知道在列表列表中提取每个子列表的第一项并将其附加到新列表的最佳方法是什么。所以如果我有:
lst = [[a,b,c], [1,2,3], [x,y,z]]
and I want to pull out a, 1and xand create a separate list from those.
我想拉出a,1并x从这些列表中创建一个单独的列表。
I tried:
我试过:
lst2.append(x[0] for x in lst)
采纳答案by alecxe
Using list comprehension:
使用列表理解:
>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']
回答by Abhishek Mittal
Your code is almost correct. The only issue is the usage of list comprehension.
你的代码几乎是正确的。唯一的问题是列表理解的使用。
If you use like: (x[0] for x in lst), it returns a generator object. If you use like: [x[0] for x in lst], it return a list.
如果你使用 like: (x[0] for x in lst),它返回一个生成器对象。如果你使用 like: [x[0] for x in lst],它会返回一个列表。
When you append the list comprehension output to a list, the output of list comprehension is the single element of the list.
当您将列表解析输出附加到列表时,列表解析的输出是列表的单个元素。
lst = [["a","b","c"], [1,2,3], ["x","y","z"]]
lst2 = []
lst2.append([x[0] for x in lst])
print lst2[0]
lst2 = [['a', 1, 'x']]
lst2 = [['a', 1, 'x']]
lst2[0] = ['a', 1, 'x']
lst2[0] = ['a', 1, 'x']
Please let me know if I am incorrect.
如果我不正确,请告诉我。
回答by Hendrik
You said that you have an existing list. So I'll go with that.
你说你有一个现有的清单。所以我会这样做。
>>> lst1 = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [1, 2, 3]
Right now you are appending the generator object to your second list.
现在您正在将生成器对象附加到您的第二个列表中。
>>> lst2.append(item[0] for item in lst)
>>> lst2
[1, 2, 3, <generator object <genexpr> at 0xb74b3554>]
But you probably want it to be a list of first items
但是您可能希望它是第一项的列表
>>> lst2.append([item[0] for item in lst])
>>> lst2
[1, 2, 3, ['a', 1, 'x']]
Now we appended the list of first items to the existing list. If you'd like to add the items themeselves, not a list of them, to the existing ones, you'd use list.extend. In that case we don't have to worry about adding a generator, because extend will use that generator to add each item it gets from there, to extend the current list.
现在我们将第一项的列表附加到现有列表中。如果您想将项目本身而不是它们的列表添加到现有项目中,您可以使用 list.extend。在这种情况下,我们不必担心添加生成器,因为扩展将使用该生成器添加它从那里获得的每个项目,以扩展当前列表。
>>> lst2.extend(item[0] for item in lst)
>>> lst2
[1, 2, 3, 'a', 1, 'x']
or
或者
>>> lst2 + [x[0] for x in lst]
[1, 2, 3, 'a', 1, 'x']
>>> lst2
[1, 2, 3]
https://docs.python.org/3.4/tutorial/datastructures.html#more-on-listshttps://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions
https://docs.python.org/3.4/tutorial/datastructures.html#more-on-lists https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions
回答by dawg
You could use zip:
你可以使用 zip:
>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)
Or, Python 3 where zipdoes not produce a list:
或者,Python 3 wherezip不生成列表:
>>> list(zip(*lst))[0]
(1, 11, 21)
Or,
或者,
>>> next(zip(*lst))
(1, 11, 21)
Or, (my favorite) use numpy:
或者,(我最喜欢的)使用 numpy:
>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1, 2, 3],
[11, 12, 13],
[21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])
回答by Christian Abbott
Python includes a function called itemgetter to return the item at a specific index in a list:
Python 包含一个名为 itemgetter 的函数,用于返回列表中特定索引处的项目:
from operator import itemgetter
Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:
向 itemgetter() 函数传递您要检索的项目的索引。要检索第一项,您将使用 itemgetter(0)。要理解的重要一点是 itemgetter(0) 本身返回一个函数。如果您将列表传递给该函数,您将获得特定项目:
itemgetter(0)([10, 20, 30]) # Returns 10
This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:
当您将它与 map() 结合使用时,这很有用,它接受一个函数作为它的第一个参数,一个列表(或任何其他可迭代的)作为第二个参数。它返回对可迭代对象中的每个对象调用函数的结果:
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:
请注意,map() 返回一个生成器,因此将结果传递给 list() 以获取实际列表。总之,您的任务可以这样完成:
lst2.append(list(map(itemgetter(0), lst)))
This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.
这是使用列表推导式的替代方法,选择哪种方法在很大程度上取决于上下文、可读性和偏好。
More info: https://docs.python.org/3/library/operator.html#operator.itemgetter
更多信息:https: //docs.python.org/3/library/operator.html#operator.itemgetter
回答by PrabhuPrakash
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
outputlist.append(values[0])
print(outputlist)
Output: ['a', 1, 'x']
输出: ['a', 1, 'x']
回答by jboi
Had the same issue and got curious about the performance of each solution.
遇到了同样的问题,并对每个解决方案的性能感到好奇。
Here's is the %timeit:
这是%timeit:
import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
The first numpy-way, transforming the array:
第一个 numpy 方式,转换数组:
%timeit list(np.array(lst).T[0])
4.9 μs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Fully native using list comprehension (as explained by @alecxe):
完全原生使用列表理解(如@alecxe 所述):
%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Another native way using zip(as explained by @dawg):
另一种本地使用方式zip(如@dawg 所解释):
%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Second numpy-way. Also explained by @dawg:
第二个numpy方式。@dawg也解释了:
%timeit list(np.array(lst)[:,0])
4.95 μs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final listsaves about one μs which is still in the 10x difference.
令人惊讶的是(好吧,至少对我而言)使用列表理解的本地方式是最快的,并且比 numpy 方式快 10 倍。在没有最终结果的情况下运行两种 numpy 方式list可以节省大约 1 微秒,这仍然是 10 倍的差异。
Note that, when I surrounded each code snippet with a call to len, to ensure that Generators run till the end, the timing stayed the same.
请注意,当我用对 的调用包围每个代码片段时len,以确保生成器运行到最后,时间保持不变。

