从文本文件中以元组而不是字符串的形式读取列表的元组-Python [英] Read in tuple of lists from text file as tuple, not string - Python

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

问题描述

我有一个要读取的文本文件,其中包含元组的行.文本中的每个元组/行均采用('描述字符串',[整数列表1],[整数列表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])
('item 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怎么办?

编辑,请使用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会产生:

>>> 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆