0

我有以下两个列表:

a = ['A-B', 'A-D', 'B-C', 'B-D', 'B-E', 'C-E', 'D-E', 'D-F', 'E-F', 'E-G', 'F-G']
b = ['7', '5', '8', '9', '7', '5', '15', '6', '8', '9', 11]

我想将这些列表转换为这样的列表:

[ ("A", "B", 7), ("A", "D", 5), ("B", "C", 8), ("B", "D", 9), ("B", "E", 7), ("C", "E", 5), ("D", "E", 15), ("D", "F", 6), ("E", "F", 8), ("E", "G", 9), ("F", "G", 11)]

问题是第一个列表需要拆分并合并到第二个列表中,并以元组作为输出。这样做的pythonic方法是什么?

4

4 回答 4

6
>>> a = ['A-B', 'A-D', 'B-C', 'B-D', 'B-E', 'C-E', 'D-E', 'D-F', 'E-F', 'E-G', 'F-G']    
>>> b = ['7', '5', '8', '9', '7', '5', '15', '6', '8', '9', 11]
>>> [x.split('-') + [int(y)] for x, y in zip(a, b)]
[['A', 'B', 7], ['A', 'D', 5], ['B', 'C', 8], ['B', 'D', 9], ['B', 'E', 7], ['C', 'E', 5], ['D', 'E', 15], ['D', 'F', 6], ['E', 'F', 8], ['E', 'G', 9], ['F', 'G', 11]]

如果你真的需要一个元组,只需使用tuple(...)构造函数,例如。

tuple(x.split('-') + [int(y)])
于 2013-04-30T11:05:03.670 回答
2

避免分裂,

[(k[0][0],k[0][-1],k[1]) for k in zip(a,b)]

甚至

[(x[0],x[-1],y) for x,y in zip(a,b)]
于 2013-04-30T11:10:55.417 回答
1
a = ['A-B', 'A-D', 'B-C', 'B-D', 'B-E', 'C-E', 'D-E', 'D-F', 'E-F', 'E-G', 'F-G']
b = ['7', '5', '8', '9', '7', '5', '15', '6', '8', '9', 11]

mylist=[]
for x,y in zip(a,b):
    tmp= x.split('-')
    mylist.append((tmp[0],tmp[1],int(y)))

mylist= [('A', 'B', 7), ('A', 'D', 5), ('B', 'C', 8), ('B', 'D', 9) , ('B', 'E',7), ('C', 'E', 5), ('D', 'E', 15), ('D', 'F', 6), ( 'E', 'F', 8), ('E','G', 9), ('F', 'G', 11)]

于 2013-04-30T11:09:12.367 回答
0
>>> [ tuple(val.split('-') + [int(b[idx])]) for idx, val in enumerate(a) ]
[('A', 'B', 7), ('A', 'D', 5), ('B', 'C', 8)]

但这真的很愚蠢,没有错误处理。

于 2013-04-30T11:11:38.710 回答