Set Comprehension in python [duplicate]

北城余情 提交于 2020-01-05 08:18:32

问题


In Python3 I wrote a simple one line code as follows :

{ 2*x  for x in {1,2,3,4} } 

but I m getting answer like this (order changed).

{8, 2, 4, 6}

Why I am getting answer {8,2,4,6} instead of {2,4,6,8}?


回答1:


That's because sets don't have any order. They're unordered collection.

help on set:

Build an unordered collection of unique elements.

If you want the order to be preserved then you can use list, tuple or collections.OrderedDict here.




回答2:


Because a set has no fixed order. Quoting the set documentation:

A set object is an unordered collection of distinct hashable objects.

Use a list or tuple if you require ordering, or use an OrderedDict() object to create unique keys that preserve ordering:

from collections import OrderedDict

ordered_unique_values = list(OrderedDict.fromkeys(2*x for x in (1,2,3,4)))


来源:https://stackoverflow.com/questions/17446289/set-comprehension-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!