Skip to content

Instantly share code, notes, and snippets.

View JackInTaiwan's full-sized avatar

Jack Cheng JackInTaiwan

View GitHub Profile
@JackInTaiwan
JackInTaiwan / python_iteration_1.py
Last active October 19, 2019 14:48
python_iteration_1.py
x = [1, 2, 3]
### Method 1: use "dir()"
print(dir(x))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
# '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
# '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
# '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
# '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
# main.py
if __name__ == '__main__':
from sample_code import x
print(x)
=================================
# sample_code.py
x = 1000
static PyObject *indexerr = NULL;
PyObject *
PyList_GetItem(PyObject *op, Py_ssize_t i)
{
if (!PyList_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
if (!valid_index(i, Py_SIZE(op))) {
prices = [
("ice cream", 80),
("bike", 20000),
("water", 30),
]
sorted_by_price = sorted(prices, key=lambda x: x[1])
print(sorted_by_price)
# > [('water', 30), ('ice cream', 80), ('bike', 20000)]
### Use recursive lambda functions to define function with multiple arguments
add = lambda x: (lambda y: x + y)
print(add(3)(5))
# > 8
### Use normal function to do the same thing
def add(x, y):
return x + y
print(add(3, 5))
### Build lambda function
lambda x: x + 1
### Build lambda function and assign it into one variable
add = lambda x: x + 1
print(add(5))
# > 6
def dog():
height = 40
def grow_up():
nonlocal height
height = height + 1
def show_height():
print("Thanks for making me growing up. I'm now {} meters !!!!".format(height))
def dog():
height = 40
def grow_up():
nonlocal height
height = height + 1
print("Thanks for making me growing up. I'm now {} meters !!!!".format(height))
return grow_up
global x
x = 10
def add_x():
x = x + 1
if __name__ == "__main__":
add_x()
def dog():
height = 40
def grow_up():
height = height + 1
return grow_up
if __name__ == "__main__":