[英]Convert list of tuple strings to tuples in Python
我将如何转换以下列表:
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])
但仍然不完整,而且变得越来越难看。
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
仍然会找出所有int,而不是手动拆分和操作字符串。
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']
。 然后,我们将列表的四个部分分配给变量,并操纵我们关心的部分以产生整数。
那么您的问题只有一行答案:
finish = [(int(s.split(' ')[1][:-1]),int(s.split(' ')[3])) for s in start]
这是一组可重用的功能,使您可以更全面地了解正在执行的操作以及注释。 如果是这样,非常适合初学者!
请注意,这是您所寻找的非常简陋,肮脏的,非Python版本,并且未优化。 帕特里克·哈夫(Patrick Haugh)和摩西·科利多(Moses Koledoye)都拥有更加简单,直接的几行答案,这些答案极其精妙! 但是,这可以通过输入其他列表/数组作为参数来重用。
我打算添加此内容的目的是通过“打开”流程并逐步进行,以帮助您了解将要执行的操作。
# 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)
因此,您以后可以访问返回值。
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.