Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这两段Python代码之间的区别是什么?_Python_Python 2.7 - Fatal编程技术网

这两段Python代码之间的区别是什么?

这两段Python代码之间的区别是什么?,python,python-2.7,Python,Python 2.7,这两段代码之间有什么区别?第一段代码按预期返回令牌列表,但第二段代码似乎只返回一个包含1项的列表 变量 sentences = load_parsed_example_sentences() # list of sentences # sentences are a list of BasicTokens # BasicTokens are single words aspects = ["plot"] 代码示例1: for aspect in aspects: for sentenc

这两段代码之间有什么区别?第一段代码按预期返回令牌列表,但第二段代码似乎只返回一个包含1项的列表

变量

sentences = load_parsed_example_sentences() # list of sentences
# sentences are a list of BasicTokens
# BasicTokens are single words
aspects = ["plot"]
代码示例1:

for aspect in aspects:
    for sentence in sentences:
        aspect_tokens = sentence.get_query_tokens(aspect)
        print aspect_tokens[0]
aspect_tokens = [aspect_token for aspect in aspects for sentence in sentences for aspect_token in sentence.get_query_tokens(aspect)]
print aspect_tokens[0]
代码示例2:

for aspect in aspects:
    for sentence in sentences:
        aspect_tokens = sentence.get_query_tokens(aspect)
        print aspect_tokens[0]
aspect_tokens = [aspect_token for aspect in aspects for sentence in sentences for aspect_token in sentence.get_query_tokens(aspect)]
print aspect_tokens[0]

这两个代码段不一样吗?

两个代码段都不同

在第一个示例中,您调用
语句。get\u query\u tokens(aspect)
并打印获得的aspect token的第一个实例


在第二个示例中,您使用列表生成器构造来构建方面标记数组,并打印出第一组标记。

它们不是等价的。
aspect_tokens = [sentence.get_query_tokens(aspect)[0] for aspect in aspects for sentence in sentences]
print aspect_tokens
第一步迭代
方面
句子
,并在每个步骤创建一个标记列表。然后打印列表中的第一个令牌。但它每一步只执行一次。
第二种方法创建一个列表,它将
get\u query\u令牌
生成的每个列表放入其中。然后在最后打印一组令牌。

我通常非常喜欢列表理解,但我认为在这种情况下,不应该使用列表理解,因为这样会使代码更难阅读。

您的第一个示例将每个
句子
每个
方面
打印一次,因此您总共将获得
方面*len(句子)
打印(假设
方面
句子
是列表)。您的第二个示例只有一个
打印
,因此它将只打印一个元素

您是否希望在每个示例执行后,
aspect\u标记
会相同?因为它们不会相同。第一个示例在每个迭代中重新分配
aspect\u标记
,因此在循环执行后,
aspect\u标记
将等于最后计算的值,具体来说,
语句[-1]。获取查询\u标记(aspect[-1])

我正在破译你想要的可能是:

代码示例1 代码示例2
这两个示例将产生相同的
aspect\u标记列表。

您能提供一个“工作”代码吗?例如,适当的变量
aspects
句子
。您不是在
[句子.为aspects中的aspect获取\u查询\u标记(aspect)[0]以使其相同吗?