在Python中将元组字符串列表转换为元组

时间:2017-01-24 16:15:09

标签: python python-2.7 python-3.x

我如何转换以下列表:

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

到以下元组列表:

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

我开始尝试这个:

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

但仍未完成且变得丑陋。

4 个答案:

答案 0 :(得分:2)

re.findall有机会和列表理解

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)]

如果初始列表的结构发生变化,re.findall仍会消除所有整数,而不是手动拆分和操纵字符串。

答案 1 :(得分: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使用split将每个字符串拆分为一个列表['foo', '1/', 'bar', '2']。然后我们将列表的四个部分分配给变量,并操纵我们关心的那些部分来生成整数。

答案 2 :(得分:2)

你的问题有一个答案:

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

答案 3 :(得分:1)

这是一组可重复使用的功能,可让您更全面地了解自己正在做的事情,并完成评论。如果是这样的话,对初学者来说是完美的!

请注意,这是一个非常简单,肮脏,无声的版本,你可能正在寻找,它是未经优化的。帕特里克·霍(Patrick Haugh)和摩西·科莱多耶(Moses Koledoye)都有更简单,更直接,更少线的答案,非常pythonic!但是,通过输入其他列表/数组作为参数,可以重复使用。

我打算添加这个内容,是为了帮助您通过“开放”流程并逐步了解您将要做的事情。

# 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)

您可以有效地将函数分配给变量:

finish = Convert2Tuple(start)

因此,您可以稍后访问返回值。

干杯!

相关问题