i'm a python newbie and i want to check if a each list element is present in another list(while respecting the index) and append this element to a third list. like this. if first element of 'listy'("11-02-jeej") contains first element of list_of_dates ("11-02), i want this element "11-02-jeej" to be appended in the first list of a list of lists. the code below doesn't work for me :(
the output that i want from this code is :[["11-02-jeej"], [2apples], []]
but instead i get : [[], [], []]
thank you so much !
list_of_dates =["11-02,", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[m].append(name)
print(lst)
CodePudding user response:
There are the following issues in your code:
The input has a comma in the first string: "11-02,". As you expect this to be a prefix, I suppose that trailing comma should not be there: "11-02"
The
if
statement should be inside the inner loop, since it needs thename
variable that is assigned there.m
is not the correct index. It should bei
, so you get:lst[i].append(name)
So here is your code with those corrections:
list_of_dates =["11-02", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[i].append(name)
print(lst)
Note that these loops can be written with list comprehension:
lst = [[s for s in listy if prefix in s] for prefix in list_of_dates]
Be aware that for the given example, "2" also occurs in "11-02-jeej", so you have both "11-02" and "2" giving a match, and so that will impact the result. If you wanted "2" to only match with "2apples", then you may want to test a match only at the start of a string, using .startswith()
.