python 列表反转并合并
python list reverse and merge
我有这两个列表
a = [(0,1), (1,2), (3,4)]
b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
我需要的是检查a中的第一个元组是否存在于b中然后合并它的反向
所以预期输出是
ab = [[(3,4),(1,2),(0,1),(6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17),(3,4)]]
我的示例代码是:
import copy
ab = copy.deepcopy(b)
for coord in b:
if a[0] in coord:
#print "Yes", coord.index(a[0])
ab.insert(coord.index(a[0]), a[::-1])
print ab
但它没有给我想要的输出。那里有人可以帮忙吗?谢谢
使用列表理解重建b
:
ab = [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
a[:0:-1]
切片不仅反转 a
,它还排除了 a
的第一个元素以防止输出中出现重复:
>>> a = [(0,1), (1,2), (3,4)]
>>> b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
>>> [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
[[(3, 4), (1, 2), (0, 1), (6, 7), (8, 9)], [(4, 5), (7, 15), (20, 25)], [(18, 17), (3, 4)]]
我有这两个列表
a = [(0,1), (1,2), (3,4)]
b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
我需要的是检查a中的第一个元组是否存在于b中然后合并它的反向 所以预期输出是
ab = [[(3,4),(1,2),(0,1),(6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17),(3,4)]]
我的示例代码是:
import copy
ab = copy.deepcopy(b)
for coord in b:
if a[0] in coord:
#print "Yes", coord.index(a[0])
ab.insert(coord.index(a[0]), a[::-1])
print ab
但它没有给我想要的输出。那里有人可以帮忙吗?谢谢
使用列表理解重建b
:
ab = [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
a[:0:-1]
切片不仅反转 a
,它还排除了 a
的第一个元素以防止输出中出现重复:
>>> a = [(0,1), (1,2), (3,4)]
>>> b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
>>> [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
[[(3, 4), (1, 2), (0, 1), (6, 7), (8, 9)], [(4, 5), (7, 15), (20, 25)], [(18, 17), (3, 4)]]