She*_*vRD 1 python algorithm list
我有一个包含k元素的列表。
我想用x,y对形成另一个列表,其中y值是x值右侧索引中的元素。
例如:
我有一个包含 4 个元素的列表:4, 8, 7, 1
我需要用这样的对创建一个对列表:
(4, 8), (4, 7), (4, 1), (8, 7), (8, 1) (7, 1)
我在这里使用 python 是我的代码:
list1 = list(map(int,input().strip().split()))[:k]
list2 = [(val,val1) for val in person1 for val1 in person2[1:]]
Run Code Online (Sandbox Code Playgroud)
您可以使用combinations()内置模块itertools来做到这一点:
from itertools import combinations
lst = [4, 8, 7, 1]
print(list(combinations(lst, 2)))
Run Code Online (Sandbox Code Playgroud)
输出:
[(4, 8), (4, 7), (4, 1), (8, 7), (8, 1), (7, 1)]
Run Code Online (Sandbox Code Playgroud)