[英]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:
我们可以为此使用 fileinput.input,并使用 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.我添加了 ID 以更清楚地显示哪些板匹配或不匹配,但如果解决方案需要省略它们,您可以删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.