我有这两个列表
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)]]
关于python 列表反转和合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33052175/