I have a list and I need to get certain elements out of it. The way I did it was to compare the second list to the first list and then append to a third list. Here is my code:
l1 = ["0 = 0","1 = 1","2 = 2", "And",
"Something", "Wicked", "This", "Way", "Comes",
f"zero.0 = 0", f"one.0 = 1", f"two.0 = 2",
f"zero.1 = 0", f"one.1 = 1", f"two.1 = 2",
f"zero.2 = 0", f"one.2 = 1", f"two.2 = 2",
"purple", "monkey", "dishwasher"]
l3 = []
for element in l1:
for i in range(3):
l2 = [f"zero.{i} = 0", f"one.{i} = 1", f"two.{i} = 2"]
for j in l2:
if j in element:
l3.append(element)
The results of this nested for loop is:
['zero.0 = 0', 'one.0 = 1', 'two.0 = 2', 'zero.1 = 0', 'one.1 = 1', 'two.1 = 2', 'zero.2 = 0', 'one.2 = 1', 'two.2 = 2']
The result is exactly what I want but I'm looking for a more Pythonic way of writing this. Any help would be greatly appreciated.
idefined in the second list? \$\endgroup\$iin theforloopfor i in range(3):\$\endgroup\$l2outside of your loop. \$\endgroup\$