获取列表理解对象

Get list comprehension object

我是故意在 python 犯罪的。这是一种糟糕的做法。 这里的目标是被诅咒的代码。全部在一条线上。

下面基本都有了

with open("file") as f:
    [int(x) for x in [y for y in f.read().split()]

我无法使用

with open("file") as f:
    a = f.read().split()
    [x for x in [(a[i-1, e]) for i, e in enumerate(a) if i > 0] ...]

因为目标是将它放在一行中(除了 with open)

我想从原始对象 return 当前元素和前一个或下一个元素。

为了说明清楚。

a = [1, 2, 3, 4, 5]

之后的非法代码会return

[(1, 2), (2, 3), (3, 4), (4, 5), (5, ?)]

所以这里的重点不是生产代码。这纯粹是看我们能把语言虐到什么地步。

到目前为止,我发现 https://code.activestate.com/recipes/204297/ 引用了 python2 中 local 的使用,在仔细研究之后,我发现它的界面有点不同。 我已经能够在内存中获取该对象,但我不知道如何实际使用这个对象。

local()['.0']

大部分属性好像都没有了,没有__self__调用。

请分享你最讨厌的想法。

通常,我会在生成器上使用 tee and islice 来做这样的事情:

from itertools import tee, islice

with open("file") as f:
    a, b = tee(f.read().split())
    b = islice(b, 1, None)
    list(zip(a, b))

您可以使用(滥用)walrus operator (:=):

将其转换为单行
list(zip((k := tee(f.read().split()))[0], islice(k[1], 1, None)))

结果是

[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

如果要填充最后一个元素,请使用zip_longest instead of zip:

from itertools import tee, islice, zip_longest
...
    list(zip_longest((k := tee(f.read().split()))[0], islice(k[1], 1, None), fillvalue='?'))

本例中的结果是

[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, '?')]

以这种方式使用迭代器而不是列表的好处是,虽然 f.read().split() 是一个已知长度的序列,但 teeislice 将适用于任何可迭代对象,甚至如果长度未知。