查找组合的列表项对

时间:2017-12-29 09:08:57

标签: python list combinations

我有一个输入列表,

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

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

5 个答案:

答案 0 :(得分: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)]

或者,您可以通过使用基于位置的索引完全摆脱zipsuggested 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]')

答案 1 :(得分: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)]

答案 2 :(得分: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)

答案 3 :(得分:0)

{{1}}

答案 4 :(得分: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])
相关问题