如何将列表列表变成元组列表?

时间:2019-04-23 19:45:40

标签: python list tuples

制作此列表列表时有些麻烦

triangles= [[0, 30, 31], [2, 32, 38], [3, 24, 46], [4, 14, 27], [10, 18, 48], [12, 21, 35], [15, 39, 45], [17, 32, 38], [19, 32, 38], [21, 43, 44], [29, 43, 44]]

进入这样的列表:

[(0,30),(30,31),(0,31),(2,32),(32,38),(2,38).. etc]

我已经尝试过:

c_list=list(nx.clique.enumerate_all_cliques(G))
triangles=[x for x in c_list if len(x)==3]
for [u,v,w] in triangles:
    print((u,v),(v,w),(u,w))

因为“三角形”是在图中形成三角形的节点的列表,因此我需要边,以便可以绘制三角形。但是,我无法使用此代码,因为它没有类型。那么如何将其转换为元组列表?

4 个答案:

答案 0 :(得分:2)

triangles = [[0, 30, 31], [2, 32, 38], [3, 24, 46], [4, 14, 27], [10, 18, 48], [12, 21, 35], [15, 39, 45], [17, 32, 38], [19, 32, 38], [21, 43, 44], [29, 43, 44]] 
y = list()
for i in triangles:
  y.append((i[0], i[1]))
  y.append((i[1], i[2]))
  y.append((i[0], i[2]))
print(y)

输出:[(0, 30), (30, 31), (0, 31), (2, 32), (32, 38), (2, 38), (3, 24), (24, 46), (3, 46), (4, 14), (14, 27), (4, 27), (10, 18), (18, 48), (10, 48), (12, 21), (21, 35), (12, 35), (15, 39), (39, 45), (15, 45), (17, 32), (32, 38), (17, 38), (19, 32), (32, 38), (19, 38), (21, 43), (43, 44), (21, 44), (29, 43), (43, 44), (29, 44)]

答案 1 :(得分:2)

>>> c_list = [[0, 30, 31], [2, 32, 38], [3, 24, 46], [4, 14, 27], [10, 18, 48], [12, 21, 35], [15, 39, 45], [17, 32, 38], [19, 32, 38], [21, 43, 44], [29, 43, 44]]
>>> import itertools
>>> [t for L in c_list for t in itertools.combinations(L, 2)]
[(0, 30), (0, 31), (30, 31), (2, 32), (2, 38), (32, 38), (3, 24), (3, 46), (24, 46), (4, 14), (4, 27), (14, 27), (10, 18), (10, 48), (18, 48), (12, 21), (12, 35), (21, 35), (15, 39), (15, 45), (39, 45), (17, 32), (17, 38), (32, 38), (19, 32), (19, 38), (32, 38), (21, 43), (21, 44), (43, 44), (29, 43), (29, 44), (43, 44)]

列表理解很简单:

  • 首先,获取L中3个元素(三角形边)的每个列表c_list
  • 第二,为每个Litertools.combinations创建边的组合;
  • 第三,将列表与所有组合一起打包。

答案 2 :(得分:0)

triangles =  [[0, 30, 31], [2, 32, 38], [3, 24, 46], [4, 14, 27], [10, 18, 48], [12,21, 35], [15, 39, 45], [17, 32, 38], [19, 32, 38], [21, 43, 44], [29, 43, 44]]
edge = []
for points in triangles:
    edge.append(tuple(points[0:2]))
    edge.append(tuple(points[1:3]))
    edge.append(tuple(points[:3:2]))
print(edge)

产量输出:

[(0, 30), (30, 31), (0, 31), (2, 32), (32, 38), (2, 38), (3, 24), (24, 46), (3, 46), (4, 14), (14, 27), (4, 27), (10, 18), (18, 48), (10, 48), (12, 21), (21, 35), (12, 35), (15, 39), (39, 45), (15, 45), (17, 32), (32, 38), (17, 38), (19, 32), (32, 38), (19, 38), (21, 43), (43, 44), (21, 44), (29, 43), (43, 44), (29, 44)]

答案 3 :(得分:0)

只需稍作更改,即可获得元组列表:

triangles= [[0, 30, 31], [2, 32, 38], [3, 24, 46], [4, 14, 27], [10, 18, 48], [12, 21, 35], [15, 39, 45], [17, 32, 38], [19, 32, 38], [21, 43, 44], [29, 43, 44]]

for [u,v,w] in triangles:
    element = [(u,v),(v,w),(u,w)]
    print(type(element))
    for item in element:
        print(type(item))

输出将类似于:

<class 'list'>
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
<class 'list'>
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
...