简体   繁体   English

特定列表理解

[英]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?我尝试使用如何朗读 Python 列表理解来解码以下列表理解? , 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 :这是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.所有使用后split分裂逗号出来。

Basically, you've got this:基本上,你有这个:

For each character ( c ) in the sentence ( sen ), create a list [',', character] .对于sentence ( sen ) 中的每个character ( c ),创建一个列表[',', character]

If character is a letter or number ( .isalnum() ), add the character to the list being built by the comprehension.如果character是字母或数字( .isalnum() ),则将该字符添加到.isalnum()构建的列表中。 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.这里的技巧是[",",c][int(c.isalnum())]实际上是一个切片,使用isalnum()的真值,转换为 int,作为零索引或一切片的索引。

So, basically, if c , is the character "b", for example, you have [',', character][1].因此,基本上,如果c是字符“b”,例如,您有 [',', character][1]。

Hope this helps.希望这可以帮助。

PS In my example, I'm using 'sen = 'i love dogs.' PS 在我的示例中,我使用的是“sen = '我爱狗”。 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', '']

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

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