查找组合的列表项对

Viv*_*nan 2 python combinations list

我有一个输入列表,

n = [0, 6, 12, 18, 24, 30, 36, 42, 48] 
# Here, the list is multiples of 6 
# but need not always be, could be of different numbers or unrelated.
Run Code Online (Sandbox Code Playgroud)

现在我想从列表中生成一对数字,所以输出是,

output = [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]
Run Code Online (Sandbox Code Playgroud)

我有以下片段来完成它.

zip([(i+1) for i in n[:-1]], n[1:])
Run Code Online (Sandbox Code Playgroud)

出于好奇,我想知道其他方法而不是我的方法!

cs9*_*s95 5

你现在拥有的是非常好的(在我的书中).虽然,您可以替换n[:-1]with n,因为zip执行"尽可能短的压缩" - 拉到两个列表中较短的一个 -

>>> list(zip([1, 2, 3], [4, 5]))
[(1, 4), (2, 5)]
Run Code Online (Sandbox Code Playgroud)

所以,您可以将表达式重写为 -

list(zip([(i+1) for i in n], n[1:]))
Run Code Online (Sandbox Code Playgroud)

为了简洁.放弃list(..)for python 2.

另一种方法(由RoadRunner建议)将把列表理解带出来,并且zip-

>>> [(x + 1, y) for x, y in zip(n, n[1:])]
[(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过使用基于位置的索引zip完全摆脱(如splash58所示) -

>>> [(n[i] + 1, n[i + 1]) for i in range(len(n) - 1)]
[(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用函数式编程范例,map-

>>> list(zip(map(lambda x: x + 1, n), n[1:]))
[(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]
Run Code Online (Sandbox Code Playgroud)

你的列表组件做了同样的事情,但可能更慢!


最后,如果您使用pandas(我最喜欢的库),那么您可以利用IntervalIndexAPI -

>>> pd.IntervalIndex.from_breaks(n, closed='right')
IntervalIndex([(0, 6], (6, 12], (12, 18], (18, 24], (24, 30], (30, 36], (36, 42], (42, 48]]
              closed='right',
              dtype='interval[int64]')
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.与熊猫很好,并了解`zip`功能 (2认同)