Python compares whether two lists or text contents are the same - code implementation

1. Basic version - check whether two lists contain the same value (the position of the same value in different lists may be different), and output the number and value of different contents;

a=[6,5,4,3,2,1]
b=[1,2,9]
for i in range(0,len(a)):
    if a[i] not in b:
        print("a有b没有","位置",i,"值",a[i])
print("---------")
for i in range(0,len(b)):
    if b[i] not in a:
        print("b有a没有","位置",i,"值",b[i])

程序运行结果:
a有b没有 位置 0 值 6
a有b没有 位置 1 值 5
a有b没有 位置 2 值 4
a有b没有 位置 3 值 3
---------
b有a没有 位置 2 值 9

2. Advanced version - Compare two txt texts to see if they are the same, and output the differences;

    There are two txt files, namely "Like Dance.txt" and "Like Music.txt";

    

    

   The code is implemented as follows:

'''比较两个文本内容'''
f_new=open('喜欢音乐.txt','r')
a=f_new.readlines()
f_old=open('喜欢舞蹈.txt','r') #以读取模式打开txt,python自带的读取文件方式
b=f_old.readlines()     #读取txt里所有行,并存储在变量b中
for i in range(0,len(a)):
    if a[i]!='\n':   #readlines会将换行读取成'\n'存储下来,因此比较时略过'\n'
        if a[i] not in b:
            print("只喜欢音乐不喜欢舞蹈",i,a[i])
print('--------------')
for i in range(0,len(b)):
    if b[i] !='/n':
        if b[i] not in a:
            print("只喜欢舞蹈不喜欢音乐",i,b[i])

The result of running the program is:

只喜欢音乐不喜欢舞蹈 0 Tom 

只喜欢音乐不喜欢舞蹈 1 Amy

只喜欢音乐不喜欢舞蹈 2 Tony

--------------
只喜欢舞蹈不喜欢音乐 2 Jenny

只喜欢舞蹈不喜欢音乐 3 Steve

只喜欢舞蹈不喜欢音乐 4 Ali

Note that when comparing txt, using python's f.readlines will read each line as each value in the list, including the newline character '\n'. If two txt files have the same line of characters, but one has a newline character and the other does not have a newline character, the two lines will be considered different when compared at this time; this is invisible to the naked eye; at this time, you can use print to output readlines( )take a look;

3. Compare excel...TBD.

Guess you like

Origin blog.csdn.net/woshisunyizhen/article/details/103262848