0

How would I convert the following list:

start = ['foo 1/ bar 2', 'foo 2/ bar 3', 'foo 34/ bar 45']

to the following list of tuples:

finish = [(1,2), (2,3), (34,45)]

I started an attempt with this:

finish = tuple([x.translate(None,'foobar ').replace('/',',') for x in start])

but still not complete and its getting ugly.

0

4 Answers 4

2
start = ['foo 1/ bar 2', 'foo 2/ bar 3', 'foo 34/ bar 45']
finish = [(int(b[:-1]), int(d)) for a, b, c, d in map(str.split, start)]

map uses split to split each string into a list, ['foo', '1/', 'bar', '2']. Then we assign the four parts of the list to variables, and manipulate the ones we care about to produce integers.

Sign up to request clarification or add additional context in comments.

Comments

2

well there is one line answer to your question :

finish = [(int(s.split(' ')[1][:-1]),int(s.split(' ')[3])) for s in start]

Comments

2

There's a chance with re.findall and a nice list comprehension:

import re

start = ['foo 1/ bar 2', 'foo 2/ bar 3', 'foo 34/ bar 45']

r = [tuple(int(j) for j in re.findall(r'\d+', i)) for i in start]
print(r)
# [(1, 2), (2, 3), (34, 45)]

In case the structure of the initial list changes, re.findall would still fish out all ints, as opposed manually splitting and manipulating the strings.

1 Comment

I really don't get why the question is downvoted that much. And why acceptable answers are downvoted... the question is clear, and the code to achieve that is a nice listcomp. It's not like we're writing 10000 lines for the OP.
1

Here is a reusable set of functions that would enable you to more thoroughly understand what it is that you're doing, complete with comments. Perfect for a beginner, if that's the case!

Be mindful, this is a very down and dirty, unpythonic version of what you may be looking for, it is unoptimized. Patrick Haugh and Moses Koledoye both have more simplistic and straight-to-the-point, few-line answers that are extremely pythonic! However, this would be reusable by inputting other lists / arrays as parameters.

My intention for adding this is to help you understand what it is you would be doing by "opening up" the process and going step-by-step.

# Import the regular expressions
import re

# Your list
start = ['foo 1/ bar 2', 'foo 2/ bar 3', 'foo 34/ bar 45']

def hasNumbers(stringToProcess):

    """ Detects if the string has a number in it """

    return any(char.isdigit() for char in stringToProcess)

def Convert2Tuple(arrayToProcess):

    """ Converts the array into a tuple """

    # A list to be be returned
    returnValue = []

    # Getting each value / iterating through each value
    for eachValue in arrayToProcess:

        # Determining if it has numbers in it
        if hasNumbers(eachValue):

            # Replace forward slash with a comma
            if "/" in eachValue:
                eachValue = eachValue.replace("/", ", ")

            # Substitute all spaces, letters and underscores for nothing
            modifiedValue = re.sub(r"([a-zA-Z_ ]*)", "", eachValue)

            # Split where the comma is
            newArray = modifiedValue.split(",")

            # Turn it into a tuple
            tupledInts = tuple(newArray)

            # Append the tuple to the list
            returnValue.append(tupledInts)

    # Return it!
    return returnValue

# Print that baby back to see what you got
print Convert2Tuple(start)

You can effectively assign the function to a variable:

finish = Convert2Tuple(start)

So you can access the return values later.

Cheers!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.