Python 如何在列表中选择元组的项?
我在文件日志中有以下数字列表:Python 如何在列表中选择元组的项?,python,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 (lin
[(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])
及
我试过使用lambda、map、filter…但我不知道这段代码中有什么机会。谁能帮帮我吗?有人能告诉我该怎么做吗?您可以使用
ast.literal\u eval
,将访问存储在每个列表中的元组的每个项目解包,并使用以下方法打印:
如果要存储所有元组的列表:
tups = [literal_eval(line.rstrip())[0] for line in f]
print(tups)
[(1, 1), (11, 11), (157, 208), (222, 224), (239, 239), (265, 268)]
:
安全地计算表达式节点或包含Python文本或容器显示的Unicode或Latin-1编码字符串。提供的字符串或节点只能由以下Python文本结构组成:字符串、数字、元组、列表、dicts、boolean和None
手动执行此操作时,您需要在剥离换行符后索引2:-2,在、
和上拆分,并将映射到int:
for line in f:
a,b =(map(int,line.rstrip()[2:-2].split(",")))
print("x = {}\ny = {}".format(a,b))
或使用str.translate删除逗号、括号等:
with open('list.log') as f:
for line in f:
a,b = map(int,line.translate(None,"()[],").split())
print("x = {}\ny = {}".format(a,b))
这个怎么样:
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())
为什么我的代码只删除了四个字符中的两个?@MalikBrahimi,因为您忘记了换行符,parse=line.strip(“()[]\n”).split(“,”)
,这也不起作用。它实际上会切换到另外两个字符。使用literal\u eval()
是一个很好的方法。然而,打印(a,b)
很可能会产生类似于(1,1)
,(11,11)
,等等的输出,因为从OP问题中的代码来看,看起来他们使用的是Python 2。除此之外,他们希望每一对产生类似于x=1
&y=1
@martineau的内容,是的,重读这个问题OP似乎确实想要格式化输出,所以我添加了str.format
你将有一个额外的)
你需要在索引之前去掉换行符
with open('list.log') as f:
for line in f:
a,b = map(int,line.translate(None,"()[],").split())
print("x = {}\ny = {}".format(a,b))
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]
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())