返回列表列表中每个列表的元素范围

发布于 2024-09-29 14:25:58 字数 176 浏览 1 评论 0原文

从列表 mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 如何获取由第一个列表组成的新列表每个“内部”列表的两个元素 ei newlist = [[1, 2], [4, 5], [7, 8]]?是否有一个单行代码可以有效地完成此操作(对于大型列表)?

From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large lists of lists)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

氛圍 2024-10-06 14:25:58

最简单的方法可能是使用列表理解:

newlist = [sublist[:2] for sublist in mylist]

The easiest way is probably to use a list comprehension:

newlist = [sublist[:2] for sublist in mylist]
柠檬色的秋千 2024-10-06 14:25:58

快速回答:

first_two = [sublist[:2] for sublist in mylist]

如果可以有一个元组列表,那么更快的答案(根据我的测量值是 2 倍):

import operator
map(operator.itemgetter(0, 1), mylist)

测量值:

t = timeit.Timer("[i[:2] for i in ll]", "ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t.timeit(10000)
>>> 2.2732808589935303

t2 = timeit.Timer("map(operator.itemgetter(0, 1), ll)", "import operator; ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t2.timeit(10000)
>>> 1.3041009902954102

Quick answer:

first_two = [sublist[:2] for sublist in mylist]

If having a list of tuples is ok, then a faster answer (2x by my measurements):

import operator
map(operator.itemgetter(0, 1), mylist)

Measurements:

t = timeit.Timer("[i[:2] for i in ll]", "ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t.timeit(10000)
>>> 2.2732808589935303

t2 = timeit.Timer("map(operator.itemgetter(0, 1), ll)", "import operator; ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t2.timeit(10000)
>>> 1.3041009902954102
携君以终年 2024-10-06 14:25:58

使用列表理解。

 newlist = [x[:2] for x in mylist]

Use list comprehension.

 newlist = [x[:2] for x in mylist]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文