简体   繁体   中英

Convert list of tuple strings to tuples in Python

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.

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.

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.

那么您的问题只有一行答案:

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM