开发者

Range in Python

开发者 https://www.devze.com 2023-03-25 20:32 出处:网络
I want to list numbers in rang开发者_开发知识库e and I want to find out the amount of numbers in range.

I want to list numbers in rang开发者_开发知识库e and I want to find out the amount of numbers in range.

For Example:

X = (5,6,5,1,2,3,4,5,6,7)
Y = (5, 5, 5,5 5,5 5,5 5)
range(X) # Want to know how many numbers in X.

If you guys could help it would be great.


Given the tuple or list X:

>>> X = (5,6,5,1,2,3,4,5,6,7)
>>> X
(5, 6, 5, 1, 2, 3, 4, 5, 6, 7)

You find the number of elements with the len function:

>>> len(X)
10

If you want to find the number of unique elements, create a set and look at its length:

>>> set(X)
set([1, 2, 3, 4, 5, 6, 7])
>>> len(set(X))
7

The range (defined mathematically) of the set of numbers can be found with the max and min functions:

>>> (min(X), max(X))
(1, 7)
>>> max(X) - min(X)
6


Are you looking for:

X = (5,6,5,1,2,3,4,5,6,7)
range = max(X) - min(X)


filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true.

So you can do filter(range(2, 10).__contains__, x), which will return the elements in x which are in range(2, 10).

If you want to narrow this down to unique elements, call set:

set(filter(range(2, 10).__contains__, x))

Finally, if you want the number of these elements, simply call len:

len(filter(range(2, 10).__contains__, x))

this will return the number of elements in array x which are in range 2 to 10.


I'm not sure I understand your question, but the number of numbers in X is the length of X:

len(X)


I'm not sure if I understand exactly what you want, but to get the mathematical range:

max(X) - min(X)

Were max() gets the highest value and min() gets the lowest one.

0

精彩评论

暂无评论...
验证码 换一张
取 消