在 python 中打印子列表

Print sublists in python

我正在尝试打印 python 中的列表列表,如下所示:

for location in latLongList:
    print ' '.join(map(str, location))

打印出来:

40.0349216312 -75.1900864349 Paved 4 0.156150432289
39.9531308619 -75.1629612614 Paved 3 0.170932927052
39.9610355788 -75.1725011285 Paved  0.17296824247
39.9788367755 -75.2123945669 Paved  0.196740550111
39.9467944475 -75.2092212039 Paved 33 0.210834020854
39.94626513 -75.2089212417 Paved 5 0.210899309368
39.9373184367 -75.2341880089 Grass  0.236747322815
39.9413269464 -75.2383849209   0.238056333485

这很好用,但我想排除每行中的最后一个数字(这是每个子列表中的最后一个数字)。我还希望能够允许用户指定要打印的行数。他们通过命令行输入该数字,并将其存储在名为 sizeOfList 的变量中。在 python 中是否有一种简单的方法可以做到这一点?任何帮助将不胜感激!

可以使用内置函数enumerate获取latLongList中每个location的索引,然后只打印索引较小的location比用户所需的数量 (sizeOfList)。然后,为了排除每个子列表中的最后一项(每个 location),您可以从子列表中取出一部分直到但不包括最后一项(位于索引 -1 处)。

for i, location in enumerate(latLongList):
    if i < sizeOfList:
        print ' '.join(map(str, location[:-1]))

@Hackaholic 对此方法进行了改进,使代码更简洁并且可能更快(由于迭代次数更少 locations):

for location in latLongList[:sizeOfList]:
    print ' '.join(map(str, location[:-1]))

此处,仅从latLongList中取出用户所需数量(sizeOfList)内的项目。不再需要 enumerate.

最好这样尝试:

for location in latLongList[:sizeOfList]:
    print ' '.join(map(str, location[:-1]))

这应该可以解决两个问题:

print '\n'.join('{} {} {}'.format(*location) for location in latLongList[:sizeOfList])

这个解决方案非常 Pythonic。使用 str.format() 无需使用 map(str, ) 将所有内容转换为字符串(str.format() 会自动为您完成此操作)。此外,无需为每个位置对子列表进行切片以消除最后一个元素,因为 str.join() 会自动忽略列表的其余部分。最后,它将打印调用次数从 sizeOfList 次减少到一次。 str.join() 操作很快,因为它加入的是迭代器而不是列表。

尽情享受吧!

你可以这样做:

# this import needs to be first
from __future__ import print_function

for location in latLongList[:sizeOfList]:
    print(*location[:-1])

__future__ 导入使 print 成为一个函数,因此您可以执行 print(*foo)。就像 print(foo[0], foo[1], ...).

首先,要打印除最后一个元素以外的所有内容,您将列表切片以包含除最后一个元素以外的所有内容:location[:-1]。 (切片在库参考中 Using Python as a Calculator; for full details see Sequence Types 的教程中进行了解释。)

然后,为了在一定数量的行之后停止,您将行列表切片:latLongList[:sizeOfList].

所以:

for location in latLongList[:sizeOfList]:
    print ' '.join(map(str, location[:-1]))

如果列表实际上不是一个列表,而是一个迭代器(或者如果您正在编写需要同时使用两者的通用代码),或者如果您担心复制部分的内存浪费列表(比如因为你想要前 2 亿行),你可以使用 islice,它解决了这两个问题:

from itertools import islice
for location in islice(latLongList, sizeOfList):
    print ' '.join(map(str, location[:-1]))