【问题标题】:Confused with the outcome of this list comprehension对这个列表理解的结果感到困惑
【发布时间】:2018-11-30 00:12:03
【问题描述】:

我有一个texts,它是一个句子列表,这段代码应该删除文本中的数字:

[''.join(c for c in x if c not in '0123456789') for x in texts]

而且它有效。

现在,x in texts 表示texts 列表中的每个句子。 c for c in x 意味着每个 x 句子中的每个单词?我很困惑,因为这样的事情不起作用:

[c for c in x for x in texts]
# or
[c for c in (x for x in texts)]

从每个句子中创建每个单词的列表。

[''.join(c for c in x if c not in '0123456789') for x in texts]不是先把句子拆成词吗?我想得越多,我就越困惑。我很想澄清一下。

【问题讨论】:

  • 如果您想拆分获取单词,请使用texts.split()。但除非这些词是数字,否则 if c not in 将不起作用。

标签: python list list-comprehension


【解决方案1】:

for c in x 其中 x 是一个字符串,表示获取字符串的每个字符,而不是每个单词。

换句话说,字符串是字符序列。

【讨论】:

  • 嗯,对。我知道了。但是为什么[c for c in x for x in texts][c for c in (x for x in texts)] 不起作用呢?它应该给我一个所有字符的列表?
  • @Huzo 语法错误。使用双重列表理解时,您必须反转 for:[c for x in texts for c in x]
猜你喜欢
  • 2012-03-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多