在python中设置理解 [英] Set Comprehension in python

查看:44
本文介绍了在python中设置理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python3 中我写了一个简单的一行代码如下:

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}

为什么我得到的答案是 {8,2,4,6} 而不是 {2,4,6,8}?

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

推荐答案

那是因为集合没有任何顺序.它们是无序集合.

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

set 的帮助:

构建一个无序独特元素的集合.

Build an unordered collection of unique elements.

如果您希望保留订单,则可以在此处使用 listtuplecollections.OrderedDict.

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

这篇关于在python中设置理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆