dlang17 dlang17 - 1 month ago 8
Python Question

How to use only the first few characters of an entry in a list to compare to another list - python

Sorry for the title gore.... So I have 2 lists, one of parts names and one is a shortened list of parts. I am trying to see if an entry in list B exists in the first few characters of an entry in list A. if it does, then output the entry of list A.

This is what I've been working with thus far:

index = 0
for x in data2:
if x in Part_List[index][:8]:
print ("nanners")
d = Part_List[index]
index += 1
else:
return


EDIT:
data2 = ['12345678', '23456789', '34567890']

Part_List = ['12345678 - Nanners', '23456789 - Nannu Nannu', '34567890 - ROFL Stomp']

Answer Source

The easiest way you can use:

part_list = {'lorem':1,'ipsum':2,'dolor':3}
list1 = ['loremx','ipsumxx','dolorxxx']

for x in list1:
    for key in part_list.keys():
        if x[:4] == key[:4]:
            print x,key,part_list[key]