【问题标题】:Make a list from some of the properties of other list从其他列表的一些属性中创建一个列表
【发布时间】:2013-05-06 21:17:41
【问题描述】:

我有一个包含其他列表的列表,并且想仅从其他列表中的第 n 个项目创建一个新列表。

my_list = [[1,2,3],['a','b','b'],[100,200,300]]

new_list = make_new_list(mylist, index=2)

new_list = [2,'b',200]

我知道如何设计一个获取所有第二个元素的函数,但我也知道总有一些 Pythonic 列表理解可以更顺利地完成此操作。什么是列表理解?

【问题讨论】:

  • 用 Python 写下你的想法,它可能是正确的 :)
  • 在 90% 的编程语言中,索引从 0 开始,而不是 1,因此您应该写为 make_new_list(mylist, index=1)

标签: python list


【解决方案1】:

这很简单:

new_list = [x[1] for x in my_list]

注意,在python中,索引从0开始,所以第二个元素在索引1处。

【讨论】:

  • 我觉得这个答案我们已经听过一千遍了,我们如何让这个答案更容易被搜索到?
  • @phant0m:也许可以通过添加指向一些评价最高的列表理解答案(12)和相关PEP 202的链接。
【解决方案2】:

你可以用列表推导来做到这一点,或者你可以使用 python 的 map 函数:

my_list = [[1,2,3],['a','b','b'],[100,200,300]]
newlist = map(lambda x: x[1], my_list)

如果你想要一个功能:

my_func = lambda li, index: map(lambda x: x[index], li)
newlist = my_func(my_list, 1)

【讨论】:

    【解决方案3】:

    除了使用 mgilson 建议的列表理解的版本之外,您还可以使用 operator.itemgetter:

    >>> from operator import itemgetter
    >>> map(itemgetter(1), my_list)
    [2, 'b', 200]
    

    一些时间比较:

    >>> lis = [[1,2,3],['a','b','b'],[100,200,300]]*10**5
    
    >>> %timeit [x[1] for x in lis]
    10 loops, best of 3: 38.6 ms per loop
    
    >>> %timeit map(itemgetter(1),lis)
    10 loops, best of 3: 43.8 ms per loop
    
    >>> %timeit map(lambda x: x[1], lis)
    10 loops, best of 3: 82.9 ms per loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2022-12-29
      • 2013-05-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多