如何在列表中选择元组的项?

时间:2015-02-11 21:42:33

标签: python

我在文件日志中有这个数字列表:

[(1, 1)]
[(11, 11)]
[(157, 208)]
[(222, 224)]
[(239, 239)]
[(265, 268)]

我希望像这样的变量值打印项目:

x = 1
y = 1

然后:返回下一行

x= 11
y = 11

返回:

x=157
y=208

可能吗?

我的代码是:

 fhand=open('list.log')
    for lines in fhand:
    print lines
    print (lines[1:1])

import re
fhand=open('list.log')
for line in fhand:
    line=line.split()
    number=map(lambda line: line.split()[0], line)
    print number

我已尝试过lambda,map,filter ......但我不知道这段代码中有什么机会。请有人帮帮我吗?有人可以告诉我该怎么做吗?

3 个答案:

答案 0 :(得分:2)

您可以使用ast.literal_eval,解压访问存储在每个列表中的元组的每个项目,然后使用str.format进行打印:

from ast import literal_eval
with open('list.log') as f:
    for line in f:
        a,b = literal_eval(line.rstrip())[0]
        print("x = {}\ny = {}".format(a,b))
x = 1
y = 1
x = 11
y = 11
x = 157
y = 208
x = 222
y = 224
x = 239
y = 239
x = 265
y = 268   

如果要存储所有元组的列表:

 tups = [literal_eval(line.rstrip())[0] for line in f]
 print(tups)
 [(1, 1), (11, 11), (157, 208), (222, 224), (239, 239), (265, 268)]

ast.literal_eval

安全地评估表达式节点或包含Python文字或容器显示的Unicode或Latin-1编码字符串。提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,dicts,布尔值和无。

手动执行此操作后,您需要在剥离换行符后将索引编入索引2:-2,将,map拆分为int:

 for line in f:
    a,b =(map(int,line.rstrip()[2:-2].split(",")))
    print("x = {}\ny = {}".format(a,b))

或使用str.translate删除逗号,parens等..:

with open('list.log') as f:
      for line in f:
        a,b = map(int,line.translate(None,"()[],").split())
        print("x = {}\ny = {}".format(a,b))

答案 1 :(得分:1)

with open('list.log') as log:
    for line in log:
        parse = line.strip('()[]\n').split(',')
        print 'x = %s' % parse[0]
        print 'y = %s' % parse[1]

答案 2 :(得分:0)

这个怎么样:

for line in fhand:
    line = line.strip(); # trim off any leading or extra whitespace including newline
    line = line[2:-2]  # trim off the leading [( and trailing )] chars
    parsed_line = line.split(',') # convert to list 
    print('x =',parsed_line[0].strip())
    print('y =',parsed_line[1].strip())