[英]Reading a txt file of a tuple of a list and an int
What would be an effective way to read in lines that are tuples of a list and an int?读取列表元组和整数行的有效方法是什么?
Each line in the txt file should look like this: txt 文件中的每一行应如下所示:
([1, 2, 3, 4, 5, 6], 1)
The first thing that came to mind was to use .split('],')
, but how do I process the tuple next?我首先想到的是使用
.split('],')
,但是接下来我该如何处理元组呢?
Thank you!谢谢!
Given that a line has been read in,鉴于已读入一行,
s = ([1, 2, 3, 4, 5, 6], 1)
We first will need to parse the tuple parenthesis.我们首先需要解析元组括号。 Based off the wording of your question, my understanding is that there is only one tuple per line.
根据您问题的措辞,我的理解是每行只有一个元组。 Therefore we can use string splicing to remove the outside parenthesis first.
因此我们可以先用字符串拼接去掉外面的括号。
s = s[1:len(s) - 1]
Giving us, [1, 2, 3, 4, 5, 6], 1
给我们
[1, 2, 3, 4, 5, 6], 1
Next we want to split the list from the int.接下来我们要从 int 中拆分列表。 You are on the right track with splitting the string using
],
as a delimiter, however in that case we would be left with,你在正确的轨道上使用
],
作为分隔符拆分字符串,但是在那种情况下我们会留下,
['[1, 2, 3, 4, 5, 6', ' 1']
A similar but slightly different approach would be to use regular expressions and split only on ,
which are directly proceeded by ]
We will use the Positive Lookbehind technique to achieve this.一种类似但略有不同的方法是使用正则表达式并仅在 split 上
,
直接由]
进行我们将使用Positive Lookbehind技术来实现这一点。
import re
s = s[1:len(s) - 1]
regex = '(?<=]), '
results = re.split(regex, s)
Now results
will be a list of two values,现在
results
将是两个值的列表,
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
1
as a string1
作为字符串Finally to split and use our tuple values we will use similar methods.最后,为了拆分和使用我们的元组值,我们将使用类似的方法。
,
as a delimiter,
作为分隔符拆分剩余的字符串As shown here,如图所示,
listResult = results[0]
listResult = listResult[1:len(listResult) - 1]
listResult = listResult.split(', ')
Lastly, our integer value can obtained by accessing results
list at index 1
,最后,我们的 integer 值可以通过访问索引为
1
的results
列表获得,
intResult = results[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.