有时我的集合是有序的,有时不是(Python) [英] Sometimes my set comes out ordered and sometimes not (Python)

查看:65
本文介绍了有时我的集合是有序的,有时不是(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道一个集合应该是一个无序列表.我正在尝试自己编写一些代码,结果发生了奇怪的事情.我的集合有时会按 1 - 100 的顺序排列(使用较大的数字时),而当我使用较小的数字时,它将保持无序.这是为什么?

So I know that a set is supposed to be an unordered list. I am trying to do some coding of my own and ended up with a weird happening. My set will sometimes go in order from 1 - 100 (when using a larger number) and when I use a smaller number it will stay unordered. Why is that?

#Steps:
#1) Take a number value for total random numbers in 1-100
#2) Put those numbers into a set (which will remove duplicates)
#3) Print that set and the total number of random numbers

import random

randomnums = 0

Min = int(1)
Max = int(100)
print('How many random numbers would you like?')
numsneeded = int(input('Please enter a number.            '))
print("\n" * 25)

s = set()

while (randomnums < numsneeded):
    number = random.randint(Min, Max)
    s.add(number)
    randomnums = randomnums + 1

print s
print len(s)

如果有人对清理我的代码有任何建议,我 100% 愿意学习.感谢您的时间!

If anyone has any pointers on cleaning up my code I am 100% willing to learn. Thank you for your time!

推荐答案

set 的文档说它是 无序集合,这仅意味着您可以对集合的元素没有特定的顺序.集合可以选择它用来保存数据的内部表示,并且当您请求元素时,它们可能以任何顺序返回.在某些情况下它们已排序的事实可能意味着该集合已选择以排序方式存储您的元素.

When the documentation for set says it is an unordered collection, it only means that you can assume no specific order on the elements of the set. The set can choose what internal representation it uses to hold the data, and when you ask for the elements, they might come back in any order at all. The fact that they are sorted in some cases might mean that the set has chosen to store your elements in a sorted manner.

集合可以根据集合中元素的数量等因素在性能和空间之间做出权衡决定.例如,它可以在列表中存储小集合,但在树中存储较大的集合.从树中检索元素最自然的方法是按排序顺序,这就是您可能会遇到的情况.

The set can make tradeoff decisions between performance and space depending on factors such as the number of elements in the set. For example, it could store small sets in a list, but larger sets in a tree. The most natural way to retrieve elements from a tree is in sorted order, so that's what could be happening for you.

另见 可以设置 Python没有排序会被视为随机排序吗?有关此的更多信息.

See also Can Python's set absence of ordering be considered random order? for further info about this.

这篇关于有时我的集合是有序的,有时不是(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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