简体   繁体   中英

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 . 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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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