0
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Where is i defined in the second list? \$\endgroup\$ – Linny Sep 23 '20 at 18:10
  • 1
    \$\begingroup\$ I defined i in the for loop for i in range(3): \$\endgroup\$ – Hellyeah Sep 23 '20 at 18:11
  • \$\begingroup\$ Ah, before your edit you had l2 outside of your loop. \$\endgroup\$ – Linny Sep 23 '20 at 18:15
  • \$\begingroup\$ @Linny Yeah, I figured an edit would clear it up a bit. Sorry about that. \$\endgroup\$ – Hellyeah Sep 23 '20 at 18:17
1
\$\begingroup\$

Unnecessary format strings

Unless you intend to format a string right then and there, you don't need an f before it.

Regex

This can be reduced to one line using regex:

import re

l3 = [item for item in l1 if re.match(r"\w{3,5}[.]\d\s[=]\s\d{1,}", item)]

Explanation

  • \w{3,5} matches any word character (equal to [a-zA-Z0-9_])

    • {3,5} Quantifier — Matches between 3 and 5 times, as many times as possible, giving back as needed (greedy)
  • Match a single character present in the list below [.]

    • . matches the character . literally (case sensitive)

    • \d matches a digit (equal to [0-9])

    • \s matches any whitespace character (equal to [\r\n\t\f\v ])

  • Match a single character present in the list below [=]

    • = matches the character = literally (case sensitive)

    • \s matches any whitespace character (equal to [\r\n\t\f\v ])

  • \d{1,} matches a digit (equal to [0-9])

    • {1,} Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
\$\endgroup\$
1
  • \$\begingroup\$ Very nice @Linny. I wanted to use l3 = [x for x in l1 if any(y in x for y in l2)] originally, but that only yielded ['zero.2 = 0', 'one.2 = 1', 'two.2 = 2'] for l3. \$\endgroup\$ – Hellyeah Sep 23 '20 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.