从文本文件中读取列表元组作为元组,而不是字符串 - Python

2022-01-20 00:00:00 python list file tuples text

问题描述

我有一个要读取的文本文件,其中包含多行元组.文本中的每个元组/行都采用 ('description string', [list of integers 1], [list of integers 2]) 的形式.文本文件可能类似于:

I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:

('项目 1', [1,2,3,4] , [4,3,2,1])
('项目 2', [ ] , [4,3,2,1])
('项目 3, [1,2] , [ ])

('item 1', [1,2,3,4] , [4,3,2,1])
('item 2', [ ] , [4,3,2,1])
('item 3, [1,2] , [ ])

我希望能够从文本文件中读取每一行,然后将它们直接放入一个函数中,

I would like to be able to read each line in from the text file, then place them directly into a function where,

function(string, list1, list2)

我知道每一行都是作为字符串读入的,但我需要以某种方式提取该字符串.我一直在尝试使用 string.split(','),但是当我点击列表时就会出现问题.有没有办法做到这一点,还是我必须修改我的文本文件?

I know that each line is read in as a string, but I need to extract this string some how. I have been trying to use a string.split(','), but that comes into problems when I hit the lists. Is there a way to accomplish this or will I have to modify my text files some how?

我还有一个元组列表的文本文件,我想以类似的形式读取它,格式为

I also have a text file of a list of tuples that I would like to read in similarly that is in the form of

[(1,2),(3,4),(5,6),...]

[(1,2),(3,4),(5,6),...]

可能包含任意数量的元组.我想在列表中阅读它并为列表中的每个元组执行一个 for 循环.我认为这两个将使用大致相同的过程.

that may contain any amount of tuples. I would like to read it in a list and do a for loop for each tuple in the list. I figure these two will use roughly the same process.


解决方案

使用 eval 怎么样?

EDIT 使用 ast.literal_eval 查看@Ignacio 的答案.

EDIT See @Ignacio's answer using ast.literal_eval.

>>> c = eval("('item 1', [1,2,3,4] , [4,3,2,1])")
>>> c
('item 1', [1, 2, 3, 4], [4, 3, 2, 1])

只有在您 100% 确定文件内容的情况下,我才建议您这样做.

I would only recommend doing this if you are 100% sure of the contents of the file.

>>> def myFunc(myString, myList1, myList2):
...     print myString, myList1, myList2
... 
>>> myFunc(*eval("('item 1', [1,2,3,4] , [4,3,2,1])"))
item 1 [1, 2, 3, 4] [4, 3, 2, 1]

查看@Ignacio 的回答...安全多了.

See @Ignacio's answer... much, much safer.

应用 ast 会产生:

Applying the use of ast would yield:

>>> import ast
>>> def myFunc(myString, myList1, myList2):
...     print myString, myList1, myList2
... 
>>> myFunc(*ast.literal_eval("('item 1', [1,2,3,4] , [4,3,2,1])"))
item 1 [1, 2, 3, 4] [4, 3, 2, 1]

相关文章