What does this "for me in [...]" loop code do?

I'm new to python, can someone explain the following syntax,

               for i in [line.split('"') for line in open('a.txt')]:
                    ......
                    ......
                    ......
+3
source share
7 answers

The file is a.txtopened and read line by line.
For each line from the file, the line is divided into "characters , which we will call these tokens.
The lines of code in the delayed block supposedly use these tokens somehow

In a nutshell, tis will analyze the contents of the file in a token, marked with newline characters or quotation marks.

If the input file is:

ab"cdef"g
h"ijk"lmno"p
q

.. the program will return tokens:

ab
cdef
g\n
h
ijk
lmno
p\n
q\n
+4
source
afile = open('a.txt')
for line in afile:
    for field in line.split('"'):
        # do something

There is really not much good reason to interpret such a simple concept in such a difficult to read expression.

+6

i fields :

file_handle = open('a.txt') # open the file
for line in file_handle: # iterate over lines in the file
    fields = line.split('"') # split line into fields
    # === End of equivalent code ===
    # Now do something with fields, for example:
    for field in fields:
        # Now do something with field

obfuscatory, . , . , , , , , .

: . (1) / ; i (2), ; (, , ) . . .

:

ab"cdef"g
h"ijk"lmno"p
q

""

['ab', 'cdef', 'g\n']
['h', 'ijk', 'lmno', 'p\n']
['q\n']

, , , , ?

+4

, .

+1

, -, , a.txt, :

"This", ""
"GO"
" "
?

['', 'This', ', ', 'test', '\n']
[' ', 'GO', '\n']
['', 'Quoted Line', '\n']
[' ? \n']

, , , ".

:

for line in open('a.txt'):
    print line

, a.txt, .

for line in open("a.txt"):
    line_parts = [line.split('"') for line in open('a.txt')]
    print line_parts

- , List Comprehension split .

, , , , , . , . :)

+1

, , , , python .

- , , , .

IE: [1,2,3], , 1 , -

originalList = [1,2,3,4]
newList = [x+1 for x in originalList]
print newList

( ), .

, , . open() . , open() return , , x .

, , split, .

( ), "", , .

, " []".

+1

"a.txt" ". . , , " i", .. .

Example:
Personal firewall "software may warn about the connection IDLE
Personal firewall "software" may warn about the connection IDLE
Personal "firewall" "software may warn about the" connection IDLE
Output:
['Personal firewall', 'software may warn about the connection IDLE \ n'] ['Personal firewall', 'software', 'may warn about the connection IDLE \ n'] ['Personal', 'firewall', '' , 'software may warn about the', 'connection IDLE \ n']
0
source

Source: https://habr.com/ru/post/1751322/


All Articles