简体   繁体   中英

How can I compare two lists of strings in python?

I am trying to compare two lists of number plates. If the number plate is in both lists I want to print the number plate and the time. And if the number plate only exists once in one of the lists, I want to print "no match". Thanks in advance. The input is like this:

1   12:00:00    45-NK-JX
1   12:00:03    DX-89-EH
1   12:00:09    DG-65-LN
2   12:00:10    RW-MJ-73
1   12:00:11    ZS-24-74
2   12:00:14    07-SD-12
2   12:00:18    GX-62-38
1   12:00:19    09-PQ-23
2   12:00:20    45-NK-JX
1   12:00:20    NG-24-DB

This is my code:

def line_information(line):
if line == '':
    return
sensor_time_plate = line.split()
sensor = sensor_time_plate[0]
time = sensor_time_plate[1]
plate = sensor_time_plate[2]
if sensor == "1":
    global plate_1
    plate_1 = plate



elif sensor == "2":
    global plate_2
    plate_2 = plate

    if set(plate_1) & set(plate_2):
        print(plate)
    else:
        print("No match")

So first we need to read the input. We can use fileinput.input for that, and split the fields with string.split:

import fileinput

set1 = set()
set2 = set()
for line in fileinput.input():
    n, time, plate = line.strip().split("\t")

    if n == "1":
        set1.add(plate)
    else:
        set2.add(plate)

After we build our sets , we can use their methods to find common and distinct elements:

matches = set1.intersection(set2)
plates_only_in_s1 = set1.difference(set2)
plates_only_in_s2 = set2.difference(set1)

print(f"Matched plates: {matches}") # {'45-NK-JX'}
print(f"Plates only in s1: {plates_only_in_s1}") # {'DG-65-LN', '09-PQ-23', 'DX-89-EH', 'NG-24-DB', 'ZS-24-74'}
print(f"Plates only in s2: {plates_only_in_s2}") # {'GX-62-38', '07-SD-12', 'RW-MJ-73'}

Alternatively, you can use an iterative approach:

for plate in set1:
    if plate in set2:
        print("Match: ", plate)
    else:
        print ("No match: ", plate)

for plate in set2:
    if plate not in set1:
        print("No match: ", plate)

Which prints:

No match:  DG-65-LN
No match:  09-PQ-23
No match:  DX-89-EH
No match:  NG-24-DB
Match:  45-NK-JX
No match:  ZS-24-74
No match:  GX-62-38
No match:  07-SD-12
No match:  RW-MJ-73

I added the IDs to make it more obvious which plates match or don't match, but you can remove them if the solutions requires omitting them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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