简体   繁体   English

列表理解python中的逗号分隔项

[英]comma separated item in list comprehension python

I have following code: 我有以下代码:

 read_files = glob.glob("*.log")

 with open("result.txt", "wb") as outfile:
    for f in read_files:
      with open(f, "rb") as infile:
         outfile.write(infile.read())       

 with open("result.txt", encoding="utf8") as f:
    b = f.readlines()   

 c=[re.findall('\d+ \d+ \d+ \d+ \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}',i) for i in b]
 c=[i  for i in c if i!=[]]

Now if i try to do the following , 现在,如果我尝试执行以下操作,

 [i[0].split(' ')[0],i[0].split(' ')[1],i[0].split(' ')[4] for i in c]

I am getting bellow error: 我收到以下错误消息:

 SyntaxError: invalid syntax

Can anybody help 有人可以帮忙吗

You need to add parentheses in order to create a list of tuples: 您需要添加括号才能创建元组列表:

[(i[0].split(' ')[0],i[0].split(' ')[1],i[0].split(' ')[4]) for i in c]

But you are still unnecessarily doing the same splitting operation multiple times for each i . 但是,您仍然不必为每个i多次执行相同的拆分操作。 For better performance and readability, you could do: 为了获得更好的性能和可读性,您可以执行以下操作:

[(x[0], x[1], x[4]) for x in (i[0].split(' ') for i in c)]

Try to surround the argument with parentheses: 尝试用括号将参数括起来:

 [ (i[0].split(' ')[0],i[0].split(' ')[1],i[0].split(' ')[4]) for i in c]

so it makes a list of tuples. 因此它列出了元组。

Can you provide more detail? 您能提供更多细节吗? Like a print out of the variable c ? 像打印出来的变量c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM