查找组合的列表项对

问题描述 投票:2回答:5

我有一个输入列表,

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.

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

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

我有以下片段来完成它。

zip([(i+1) for i in n[:-1]], n[1:])

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

python list combinations
5个回答
5
投票

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

>>> list(zip([1, 2, 3], [4, 5]))
[(1, 4), (2, 5)]

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

list(zip([(i+1) for i in n], n[1:]))

为了简洁。删除list(..) for python 2。

另一种选择(suggested by 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)]

或者,你可以通过使用基于位置的索引完全摆脱zip(如suggested by 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)]

另一种方法是使用函数式编程范例,使用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)]

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


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

>>> 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]')

3
投票

numpy的另一个接受整数加法:

import numpy as np

n = [0, 6, 12, 18, 24, 30, 36, 42, 48] 
a = np.array(n)
output = list(zip(a+1,a[1:]))

print(output)

返回:

[(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]

3
投票

添加@cᴏʟᴅsᴘᴇᴇᴅ对函数式编程范例的推荐,你也可以使用没有map()zip()来做到这一点:

n = [0, 6, 12, 18, 24, 30, 36, 42, 48] 

result = list(map(lambda x, y: (x + 1, y), n, n[1:]))

print(result)
# [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)

0
投票
n1=range(0,49)
n=n1[1::6]
x1=range(1,44)
x=x1[::6]
print (zip(x,n))

0
投票

你在找这样的东西吗?

final_list=[]
n = [0, 6, 12, 18, 24, 30, 36, 42, 48]
for i in range(0,len(n),1):
    chuck=n[i:i+2]
    if len(chuck)<2:
        pass
    else:
        final_list.append((chuck[0]+1,chuck[1]))
print(final_list)

输出:

[(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)]

你也可以在一行中做:

n = [0, 6, 12, 18, 24, 30, 36, 42, 48]
print([(n[i:i+2][0]+1,n[i:i+2][1]) for i in range(0,len(n),1) if len(n[i:i+2])==2])
© www.soinside.com 2019 - 2024. All rights reserved.