簡體   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