-2

This is more of a refactoring question, as the code works as is. But since I am still learning Python, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.

So I have the following statement:

numbers = [re.split(' ?- ?', ticket.text.strip()) for ticket in tickets]

which obviously generates a list of lists. However, I want to have just a single list of the numbers taken out from that regex.

So this is the second line of code that flattens the above list (I found this solution here, on StackOverflow btw):

flat = [item for setlist in numbers for item in setlist]

Main thing I am trying to achieve is to have this on 1 single line. Otherwise, I could of course have a normal for .. in loop, that would append each number to numbers list, but I like keeping it on 1 line.

If this is the best it can get, I would also love to know that please.. :)

7
  • 2
    This is more of a refactoring question, as the code works - This type of question would probably work much better on code view: codereview.stackexchange.com. They accept people's, working code, and could help you improve it. I suggest moving it there. Aug 26, 2016 at 14:22
  • Why are you doing this with regex?
    – Mast
    Aug 26, 2016 at 14:24
  • Because the numbers are in this format: 1 - 2 - 3 - 4 Aug 26, 2016 at 14:25
  • I have added the answer and it will work if your mentioned logic is working (though, don't know why it is down-voted). It would be great if you could also mention you content of tickets so that I could verify it Aug 26, 2016 at 14:36
  • 2
    @Mr.goosberry: this question is a bad fit for Code Review.
    – vaultah
    Aug 26, 2016 at 14:46

5 Answers 5

1

A better idea is to add another loop over re.split(' ?- ?', ticket.text.strip()) in the list comprehension:

flat = [x for ticket in tickets for x in re.split(' ?- ?', ticket.text.strip())]

It's also more efficient and cleaner.

By the way, you should use string methods instead of regex:

flat = [x.strip() for ticket in tickets for x in ticket.split('-')]

If you need to convert x to int, you may drop strip(), since int ignores leading and trailing whitespace.

flat = [int(x) for ticket in tickets for x in ticket.split('-')]
0
0

Well, let's work through this one step at a time. As a set of partially-nested for-loops, your code would be:

numbers = []
for ticket in tickets:
    numbers.append(re.split(' ?- ?', ticket.text.strip())
flat = []
for setlist in numbers:
    for item in setlist:
        flat.append(item)

Talking through it: You have a list of tickets. Each ticket becomes one setlist when you apply the regex split to it. You then want to grab all the items in the setlist and put them in a single list. You don't actually need to have a list of all the setlists (what you called numbers) at any point - that's just an intermediate stage.

Refactoring this to be completely nested:

flat = []
for ticket in tickets:
    for item in re.split(' ?- ?', ticket.text.strip()):
         flat.append(item)

Now that we have a set of completely-nested for loops, it's trivial to refactor into a list or generator comprehension:

flat = [item for ticket in tickets for item in re.split(' ?- ?', ticket.text.strip())]

It's a fairly long single line, but it is a single line.

Incidentally, a regex might not be the best way to parse out numbers like that - especially if you want the actual numbers rather than strings. re.split() is slower than str.split(), and this split is simple enough that it can be done by the latter. If the numbers are integers, try:

flat = [int(item) for ticket in tickets for item in ticket.split('-'))]

And if they're floats, try:

flat = [float(item) for ticket in tickets for item in ticket.split('-'))]

This works because the int(str) and float(str) builtins automatically ignore whitespace at the start and end of a given string, so you don't need a regex to conditionally match that whitespace. The resulting numbers can still be inserted into strings if you need to do that, and should also take up somewhat less space in memory. If the numbers are integers, you lose nothing. If they're floats, you lose very little - you lose the original precision of the number, and you might run into the limits on float size if you're working with really big or really tiny stuff (but that's unlikely - see sys.float_info for what those limits are).

-1

You can achieve it using chain and map in single line as:

list(chain(*map(lambda x: re.split(' ?- ?', x.text.strip()), tickets)))

Suggestion:

There is no need to use regex here, because you may achieve the same using split function of Python. Hence, your answer will become:

list(chain(*map(lambda x: x.text.replace(' ', '').split('-')), tickets)))

Explaination:

chain function from the itertools library is used to umwrap the list. Below is the sample example

>>> from itertools import chain
>>> my_nested_list = [[1,2,3], [4,5,6]]
>>> list(chain(*my_nested_list))
[1, 2, 3, 4, 5, 6]

Whereas map function is used to call the passed function (in this case lambda function) on each item of list.

>>> my_nested_list = [[1,2,3], [4,5,6]]
>>> map(lambda x: x[0], my_nested_list)
[1, 4]

And, split is used to split the content of string based on substring. For example:

>>> x = 'hey you - i am here'
>>> x.split('-')
['hey you ', ' i am here']  # Same answer as your regex
9
  • Updated the answer. See suggestion section. I do not think you need regex as regex are heavier compared to simple split Aug 26, 2016 at 14:43
  • The reason why I used regex was to get rid of those spaces as well. In your example too, 'hey you ' and ' i am here', both have spaces. I'd have to trim them I guess, so 2 functions in total - split + trim. Aug 26, 2016 at 14:47
  • But we are anyhow using strip to trim the white spaces. So, it won't matter. Also, I will like to mention, you can also split as .split('- ') i.e a space after - :) Aug 26, 2016 at 14:50
  • 1
    I tried that, but x.text returns html textContent. Therefore, it has tons of empty spaces like tabs and carriage returns. I would need to replace them as well. Aug 26, 2016 at 15:17
  • 1
    I implemented this approach and I will accept this one. Thanks to others for their inputs, managed to learn a thing or two. Aug 26, 2016 at 15:24
-1
sum([re.split(' ?- ?', ticket.text.strip()) for ticket in tickets], [])
6
  • This is very inefficient.
    – vaultah
    Aug 26, 2016 at 14:42
  • @vaultah I know, and? Read again what OP is asking... Main thing I am trying to achieve is to have this on 1 single line
    – BPL
    Aug 26, 2016 at 14:43
  • Yep, and it's a poor solution nevertheless.
    – vaultah
    Aug 26, 2016 at 14:44
  • @vaultah Well, that's comment is too broad. When N is small this solution will be more than good enough. Be aware you don't need always provide the most efficient solution
    – BPL
    Aug 26, 2016 at 14:48
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".
    – abarisone
    Aug 26, 2016 at 15:32
-2

Just substitute the first expression for numbers in the second expression:

flat = [item for setlist in [re.split(' ?- ?', ticket.text.strip()) for ticket in tickets] for item in setlist]
1
  • Ah I see! I was doing it without the inner square brackets. of course, this makes sense! Thank you! Aug 26, 2016 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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