猿问

请教各位大神,一个列表A=[2,3,4],如何将其转换成B=[(2,3),(3,4),(4,2)]

相当于一个无向图顶点为〔2,3,4〕,如何输出无向图的所有边……谢谢*^_^*

蔷薇之下
浏览 1954回答 3
3回答

5E

A=[2, 3, 4] newA=[] counter = 0 for x in A:     if (counter+1) == len(A):         tup = (A[counter],A[0])     else:         tup = (A[counter],A[counter+1])     newA.append(tup)     counter += 1 print newA随便写的,还可以再简化……

清波

无向图所谓无向其实就是从顶点中取出两个顶点的组合(非排列),Python中有一个专门的包是做这个的:from itertools import combinations as comb def undigraph(a):     try:         return list(comb(a,2))     except Exception as e:         print(e)          print(undigraph([2,3,4])) >>>  [(2, 3), (2, 4), (3, 4)]
随时随地看视频慕课网APP

相关分类

Python
我要回答