什么是for循环而不是列表理解?

时间:2016-07-11 18:38:53

标签: python

我遇到了一个程序,想知道没有列表推导的程序会是什么。下面显示的是代码谢谢:

sentence = input("Enter a sentence: ")
sentence = sentence.lower().split()
uniquewords = []
for word in sentence:
    if word not in uniquewords:
        uniquewords.append(word)

positions = [uniquewords.index(word) for word in sentence]
recreated = " ".join([uniquewords[i] for i in positions])

print (positions)
print (recreated)

1 个答案:

答案 0 :(得分:0)

A list comprehension can be replaced by a more-or-less equivalent for loop. Consider these two snippets:

# 1
a = [f(b) for b in expression]

# 2
a = []
for b in expression:
    a.append(f(b))

You can see how the elements of the list comprehension appear in the expanded for loop.

These two list comprehensions:

positions = [uniquewords.index(word) for word in sentence]
recreated = " ".join([uniquewords[i] for i in positions])

Are roughly equivalent to:

positions = []
for word in sentence:
    positions.append(uniquewords.index(word)
recreated_temp = []
for i in positions:
    recreated_temp.append(uniquewords[i])
recreated = " ".join(recreated_temp)