繁体   English   中英

在视觉上区分两个 python 列表的顺序?

[英]Diffing order of two python lists visually?

我有两个列表,它们具有相同的元素但顺序不同。

foo = ["A", "B", "C", "D", "E", "F"]
bar = ["C", "A", "B", "D", "E", "F"]

现在,我想知道哪些元素被交换并呈现在情节中,并提供一些视觉线索,以便更容易地发现改组。

该图应在不同元素之间使用彩色线条。 类似于下面的内容,但带有颜色和 matplotlib。

   A   B   C  D  E  F
v---\---\--^
C    A  B     D  E  F

首先,这将列出所有未映射到相同值的项目

for f, b, in zip(foo, bar):
    if f != b:
        print(f, b)

扩展 alphanimals 示例以查找位置,您可以使用 annotate 来指示数组位置,然后使用 index 来查找数组中交换的位置。

如下例所示:

import matplotlib.pyplot as plt

foo = ["A", "B", "C", "D", "E", "F"]

bar = ["C", "A", "B", "D", "E", "F"]


# put data point names on plots
for num in range(len(bar)):
    plt.annotate(bar[num], # this is the text
        (num,1), # this is the point to label
        textcoords="offset points", # how to position the text
        xytext=(0,10), # distance from text to points (x,y)
        ha='center') # horizontal alignment can be left, right or center

for num in range(len(foo)):
    plt.annotate(foo[num], # this is the text
        (num,2), # this is the point to label
        textcoords="offset points", # how to position the text
        xytext=(0,10), # distance from text to points (x,y)
        ha='center') # horizontal alignment can be left, right or center

plt.plot(foo,len(foo)*[1],'bo-')
plt.plot(bar,len(bar)*[2],'bo-')


for f, b, in zip(foo, bar):
    if f != b:
        print(f,b)
        bar_position = bar.index(f)
        foo_position = foo.index(f)

        swappositions = [bar_position,foo_position]

        plt.plot(swappositions,[1,2],'r--') # indicates dashed red line for swapped elements


#turn off ticks
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False,         # ticks along the top edge are off
    labelbottom=False) # labels along the bottom edge are off

plt.show()

产生以下情节:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM