简体   繁体   中英

Particular List Comprehension

Could any one explain how to understand this particular list comprehension.

I have tried to decode the below list comprehension using How to read aloud Python List Comprehensions? , but still not able to understand.

words  = "".join([",",c][int(c.isalnum())] for c in sen).split(",")

lets say:

sen='i love dogs'

So the output would be,

['i', 'love', 'dogs']

Here is a better way with split :

print(sen.split())

Output:

['i', 'love', 'dogs']

Explaining (your code):

  1. Iterates the string, and if the letter is nothing, like ie space etc... , make it a comma.

  2. After all of that use split to split the commas out.

Basically, you've got this:

For each character ( c ) in the sentence ( sen ), create a list [',', character] .

If character is a letter or number ( .isalnum() ), add the character to the list being built by the comprehension. Or rather:

`[',', character][1]`.

If not, take the comma (","), and add that to the list being built by the comprehension. Or rather:

`[',', character][0]`

Now, join the list together into a string:

`"".join(['I', ',', 'l', 'o', 'v', 'e', ',', 'd', 'o', 'g', 's', ','])`

becomes

`"I,love,dogs,"`

Now and split that string using commas as the break into a list:

"I,love,dogs,".split(",")

becomes

`['I', 'love', 'dogs', '']`

The trick in here is that [",",c][int(c.isalnum())] is actually a slice, using the truth value of isalnum() , converted to an int, as either the zero index or the one index for the slice.

So, basically, if c , is the character "b", for example, you have [',', character][1].

Hope this helps.

PS In my example, I'm using 'sen = 'i love dogs.' Can you spot the difference between your result and mine, and understand why it happens?

Here's code:

sen = 'I love dogs.'
words  = "".join([",",character][int(character.isalnum())] for character in sentence).split(",")
print(words)

Result:

['I', 'love', 'dogs', '']

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