问题
When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:
>> a = [x for x in [1,2,3]]
>> a
[1, 2, 3]
Equally, is the following equality guaranteed:
>> lroot = [1, 2, 3]
>> la = [x for x in lroot]
>> lb = []
>> for x in lroot:
lb.append(x)
>> lb == la
True
Specifically, it's the ordering I'm interested in here.
回答1:
Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.
回答2:
Yes, a list is a sequence. Sequence order is significant.
回答3:
It has been a while, but since I came up with a similar question myself recently, and needed a bit more explanation to understand what this comes down to exactly, I'll add my two cents, may it help someone else in the future! :) More specifically this is about the order of values resulting from a list comprehension operation.
Imagine you have the following list:
list_of_c = [a, b, c, d, e]
I want to round the variables in that list using the following list comprehension:
list_of_d = [round(value, 4) for value in list_of_c]
My question was whether this would mean that the order resulting from the list comprehension would be the following:
list_of_d = [round_a, round_b, round_c, round_d, round_e]
And the answer I received very kindly from @juanpa.arrivillaga , was that indeeded, YES that was the case!
来源:https://stackoverflow.com/questions/1286167/is-the-order-of-results-coming-from-a-list-comprehension-guaranteed