源於最近寫程序頻繁用到了list中元素兩兩組合問題,特意總結如下:
list中相鄰元素兩兩組合:
portList = ['a', 'b', 'c', 'd']
for i, p in enumerate(portList):
if i == len(portList) - 1:
break
print(p, portList[i + 1])
print("------")
#不使用內置工具實現有序排列
list1=['a','b','c','d']
list2 = []
for i in range(len(list1)):
for j in range(i+1,len(list1)):
if i != j:
list2.append((list1[i],list1[j]))
print(list2)
使用內置函數實現有序組合
import itertools
list1=['a','b','c','d']
#2指的是幾個元素組合
iter = itertools.combinations(list1,2)
print(list(iter))
#不使用內置工具實現無序排列
list1=['a','b','c','d']
list2 = []
for i in list1:
for j in list1:
if i != j:
list2.append((i,j))
print(list2)
#無序排列
import itertools
list1=['a','b','c','d']
iter = itertools.permutations(list1,2)
print(list(iter))
二、zip的妙用
l1 = ['a', 'b']
l2 = [1, 2]
l3 = ['A', 'B']
batch = (l1, l2, l3)
print(list(zip(*batch)))
運行的結果如下:
參考文獻:
https://www.cnblogs.com/angdh/p/10277829.html
https://blog.csdn.net/weixin_41576383/article/details/82290185