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

Read in tuple of lists from text file as tuple, not string - Python(从文本文件中读取列表元组作为元组,而不是字符串 - Python)

本文介绍了从文本文件中读取列表元组作为元组,而不是字符串 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要读取的文本文件,其中包含多行元组.文本中的每个元组/行都采用 ('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]

这篇关于从文本文件中读取列表元组作为元组,而不是字符串 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐