如何向前移动 python 中列表的组合?
How to get forwaard moving combination of a list in python?
我有以下列表
lst = [100,200,300,400]
我需要以下输出 [(100, 200), (200, 300), (300, 400)]
我做了一些研究并为此使用了 itertools.combinations 库
[c for c in itertools.combinations(lst, 2)]
如果我使用上面的代码,我会得到以下产生所有组合的输出。
[(100, 200), (100, 300), (100, 400), (200, 300), (200, 400), (300, 400)]
我不要所有的组合,我只想要向前移动的组合
如何获得所需的输出?
您可以使用纯 python 代码实现此目的。
lst = [100,200,300,400]
new_lst = [(lst[a],lst[a+1]) for a in range(len(lst)) if a<len(lst)-1]
print(new_lst)
输出
[(100, 200), (200, 300), (300, 400)]
AS @hilberts_drinking_problem 评论你也可以使用 <a href="https://docs.python.org/3/library/itertools.html#itertools.pairwise" rel="nofollow noreferrer">itertools.pairwise</a>
。
from itertools import pairwise
lst = [100,200,300,400]
new_list = list(pairwise(lst))
print(new_list)
输出:
[(100, 200), (200, 300), (300, 400)]
如果您使用的是 Python 3.10,则可以使用 itertools.pairwise()
。否则,您可以使用 zip()
:
lst = [100,200,300,400]
list(zip(lst, lst[1:]))
这输出:
[(100, 200), (200, 300), (300, 400)]
我有以下列表 lst = [100,200,300,400]
我需要以下输出 [(100, 200), (200, 300), (300, 400)]
我做了一些研究并为此使用了 itertools.combinations 库
[c for c in itertools.combinations(lst, 2)]
如果我使用上面的代码,我会得到以下产生所有组合的输出。 [(100, 200), (100, 300), (100, 400), (200, 300), (200, 400), (300, 400)]
我不要所有的组合,我只想要向前移动的组合 如何获得所需的输出?
您可以使用纯 python 代码实现此目的。
lst = [100,200,300,400]
new_lst = [(lst[a],lst[a+1]) for a in range(len(lst)) if a<len(lst)-1]
print(new_lst)
输出
[(100, 200), (200, 300), (300, 400)]
AS @hilberts_drinking_problem 评论你也可以使用 <a href="https://docs.python.org/3/library/itertools.html#itertools.pairwise" rel="nofollow noreferrer">itertools.pairwise</a>
。
from itertools import pairwise
lst = [100,200,300,400]
new_list = list(pairwise(lst))
print(new_list)
输出:
[(100, 200), (200, 300), (300, 400)]
如果您使用的是 Python 3.10,则可以使用 itertools.pairwise()
。否则,您可以使用 zip()
:
lst = [100,200,300,400]
list(zip(lst, lst[1:]))
这输出:
[(100, 200), (200, 300), (300, 400)]