print (list(range(6)))
[0, 1, 2, 3, 4, 5]
print (list(range(1,6)))
[1, 2, 3, 4, 5]
print (list(range(1,6,3)))
[1, 4]
>>> print (list(range(1,6,30)))
[1]
import numpy as np
print (np.arange(6))
[0 1 2 3 4 5]
Help on built-in function choice:
choice(...) method of mtrand.RandomState instance
choice(a, size=None, replace=True, p=None)
Generates a random sample from a given 1-D array
.. versionadded:: 1.7.0
Parameters
-----------
a : 1-D array-like or int
If an ndarray, a random sample is generated from its elements.
If an int, the random sample is generated as if a were np.arange(a)
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
replace : boolean, optional
Whether the sample is with or without replacement
p : 1-D array-like, optional
The probabilities associated with each entry in a.
If not given the sample assumes a uniform distribution over all
entries in a.
Returns
--------
samples : single item or ndarray
The generated random samples
Raises
-------
ValueError
If a is an int and less than zero, if a or p are not 1-dimensional,
if a is an array-like of size 0, if p is not a vector of
probabilities, if a and p have different lengths, or if
replace=False and the sample size is greater than the population
size
See Also
---------
randint, shuffle, permutation
Examples
---------
Generate a uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3)
array([0, 3, 4])
>>> #This is equivalent to np.random.randint(0,5,3)
Generate a non-uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])
Generate a uniform random sample from np.arange(5) of size 3 without
replacement:
>>> np.random.choice(5, 3, replace=False)
array([3,1,0])
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
Generate a non-uniform random sample from np.arange(5) of size
3 without replacement:
>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0])
Any of the above can be repeated with an arbitrary array-like
instead of just integers. For instance:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
dtype='|S11')
Help on function train_test_split in module sklearn.model_selection._split:
train_test_split(*arrays, **options)
Split arrays or matrices into random train and test subsets
Quick utility that wraps input validation and
``next(ShuffleSplit().split(X, y))`` and application to input data
into a single call for splitting (and optionally subsampling) data in a
oneliner.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
*arrays : sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse
matrices or pandas dataframes.
test_size : float, int or None, optional (default=0.25)
If float, should be between 0.0 and 1.0 and represent the proportion
of the dataset to include in the test split. If int, represents the
absolute number of test samples. If None, the value is set to the
complement of the train size. By default, the value is set to 0.25.
The default will change in version 0.21. It will remain 0.25 only
if ``train_size`` is unspecified, otherwise it will complement
the specified ``train_size``.
train_size : float, int, or None, (default=None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
shuffle : boolean, optional (default=True)
Whether or not to shuffle the data before splitting. If shuffle=False
then stratify must be None.
stratify : array-like or None (default=None)
If not None, data is split in a stratified fashion, using this as
the class labels.
Returns
-------
splitting : list, length=2 * len(arrays)
List containing train-test split of inputs.
.. versionadded:: 0.16
If the input is sparse, the output will be a
``scipy.sparse.csr_matrix``. Else, output type is the same as the
input type.
Examples
--------
>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
[0, 1],
[6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
[8, 9]])
>>> y_test
[1, 4]
>>> train_test_split(y, shuffle=False)
[[0, 1, 2], [3, 4]]
def fib(n):
a, b = 0, 1
while a<n:
print(a,end=' ')
a, b = b, a+b
else:
print()
fib(2000)
打印结果:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
ask_ok('Do you really want to quit?')
#调用形式还有另外两种
# ask_ok('OK to overwrite the file?', '2')
# ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
函数的默认值初始化测试
1.
a = 4
def test(arg = a):
print(arg)
a = 5
test()
#以下是打印结果,改变a的值,并不会更改arg默认参数的值
4
2.默认值只初始化一次,当默认值是可变对象时候,后续的调用可能会改变
def test(a,L=[]):
L.append(a)
print(L)
test(6)
test(6)
test(6)
#打印结果
[6]
[6, 6]
[6, 6, 6]
正常传参例子
def test(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:",test.__annotations__)
print("Arguments:", ham, eggs)
print(type(ham))
return eggs
test(1)
#打印内容
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
Arguments: tt eggs
<class 'str'>
Out[18]:
'tteggs'
异常传参例子
函数需要str类型的ham参数,但是我们传递进去int类型的ham值,这时候会有以下两种情况出现:
def test(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:",test.__annotations__)
print("Arguments:", ham, eggs)
print(type(ham))
return eggs
test(1)
#打印内容
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
Arguments: 1 eggs
<class 'int'>
Out[15]:
'eggs'
#---------------------------------------------------------------------
def test(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:",test.__annotations__)
print("Arguments:", ham, eggs)
print(type(ham))
return ham + eggs
test(1)
#打印内容
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
Arguments: 1 eggs
<class 'int'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-777b174a7f87> in <module>
4 print(type(ham))
5 return ham + eggs
----> 6 test(1)
<ipython-input-16-777b174a7f87> in test(ham, eggs)
3 print("Arguments:", ham, eggs)
4 print(type(ham))
----> 5 return ham + eggs
6 test(1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'