COMP9021 week3 notes

bases 2, 8, 16

十进制转二进制 binary

f'{23:b}'

'10111'

控制转成二进制时的位数,前面用0补全

f'{23:8b}'

'      10111'

f'{23:08b}'

'00010111'

计算出的数转二进制,三位,前面用0补足

f'{2 ** 3 -1:03b}'

从0到8转二进制

for n in range(8):

    print(f'{n:03b}')

000

001

010

011

100

101

110

111

从0-8转二进制的另一种方法

for n in range(8):

    print(n // 4, n % 4 // 2, n % 2)

从上面的number转tuple

for n in range(8):

    print(tuple(int(e) for e in f'{n:03b}'))

(0, 0, 0)

(0, 0, 1)

......

二进制转十进制 two symbols in front of the number in base 2

0b11011

二进制如何计算称为十进制:“11011”的十进制如何计算,十转二是除二取余, 二进制转十进制

1*(2**0) + 1*(2**1)+ 0*(2**2) + 1*(2**3) + 1*(2**4)

use default in base 2

int('0b11011',2)

don't have to write '0b', indispensible

int('11011',2)

十进制转八进制

f'{27:o}'


八进制转十进制

0o33

convert base 8 into base 10

int('33', 8)

int('0o33', 8)

八进制计算成为十进制

3 * (8**0)+ 3 * (8**1)

十进制转十六进制

f'{27:x}'

十六进制转十进制

0x1b

十六进制计算为十进制,b=11

11*(16**0) + 1*(16**1)

invalid literal for int() with base 10: '0b11011'

int('0b11011')


what is charater in 61

chr(61)

ask the position of the character

ord('=')

Remember: it is not consistent

'\N{large red square}'

'\N{white large square}'

'\N{black large square}'

Dictionary comprehensions

L = [1, 0, 0, 1, 1, 1, 0]

mapping = {0:'⬜', 1:'⬛'}

[mapping[x] for x in L]

Gluing all of that together

''.join([mapping[x] for x in L])

''.join(mapping[x] for x in L)

Sort the collection of things, you need to compare with something, make it sequential

sorted({3, 1, -5, 7, -6})

Just sort the keys

sorted({3:0, 1: 0, -5:'I', 7:'⬛', -6: 9.56})

Graphic

sorted({(3,0), (3,-2), (1,7), (3, 1), (1, -5)})

Cannot campare 'tuple' and 'int'

sorted({1, (2,)})

Pass float, int, and complex data into abs() function and it will return absolute value.

abs(4), abs(-4)

sorted({5, 3, 1, -5, 7, 5, -6, 5}, key=abs)

key主要用来比较元素

sorted([5, 3, 1, -5, 7, 5, -6, 5], key=abs)

how to order integers

{5, 3, 1, 5, 7, 5, 6, 5}

reverse = True降序,reverse=False升序(默认)

sorted([5, 3, 1, -5, 7, 5, -6, 5], key=abs, reverse = True)

The next() function returns the next item in an iterator.

sorted([5, 3, 1, -5, 7, 5, -6, 5], key=abs)=[1, 3, 5, -5, 5, 5, -6, 7]

The reversed() function returns a reversed(颠倒的) iterator object.

next(reversed(sorted([5, 3, 1, -5, 7, 5, -6, 5], key=abs)))

Don't want to pass two elements

def add_up(x, y):

    return x + y

sorted({(3,0), (3,-2), (1,7), (3, 1), (1, -5)}, key=add_up)

x is a tuple, so you can use[]

def add_up(x):

    return x[0] + x[1]

f = add_up

sorted({(3,0), (3,-2), (1,7), (3, 1), (1, -5)}, key=f)

sort()

list.sort(cmp=None, key=None, reverse=False)

cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。

key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。

Lambda function

A lambda function can take any number of arguments, but can only have one expression.

Syntax:

lambda arguments : expression

Add 10 to argument a, and return the result:

x = lambda a : a + 10

print(x(5))

CBA的进行排序

sorted({(3,0,2), (3,0,1), (1,7,2), (3, 1,1), (1, -5,1)}, key=lambda x: (x[2],x[1],x[0]))

使用lambda定义一个函数,确定sort的排序关键值key进行运算。

sorted({(3,0), (3,-2), (1,7), (3, 1), (1, -5)}, key=lambda x: x[0]+x[1])

# x represents {}, dictionary, is a tuple, you can point out the elements in a tuple: x[0] represents the first one, x[0] + x[1] represents the first one plus the second one, and then sort these tuples from max to min.

[(1, -5), (3, -2), (3, 0), (3, 1), (1, 7)]

Use lambda for sorting purposes, and define a function

def add_up(x):

    return x[0] + x[1]

# define function add_up(x), x=x[0] + x[1]

f = add_up

# call add_up by f

sorted({(3,0), (3,-2), (1,7), (3, 1), (1, -5)}, key=f)

# the output is same as the last one

[(1, -5), (3, -2), (3, 0), (3, 1), (1, 7)]

标准数据类型

python共有五个标准的数据类型:

Numbers 数字

String 字符串

List 列表

Tuple 元组

Dictionary 字典

List 列表

列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。

列表用 [ ] 标识,是 python 最通用的复合数据类型。

列表中值的切割也可以用到变量 [头下标:尾下标] ,就可以截取相应的列表,从左到右索引默认 0 开始,从右到左索引默认 -1 开始,下标可以为空表示取到头或尾。

加号 + 是列表连接运算符,星号 * 是重复操作。

list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

# 输出完整列表

print list

['runoob', 786, 2.23, 'john', 70.2]

# 输出列表的第一个元素

print list[0]

runoob

# 输出第二个至第三个元素

print list[1:3]

[786, 2.23]

# 输出从第三个开始至列表末尾的所有元素

print list[2:]

[2.23, 'john', 70.2]

# 输出列表两次

print tinylist * 2

[123, 'john', 123, 'john']

# 打印组合的列表

print list + tinylist

['runoob', 786, 2.23, 'john', 70.2, 123, 'john']

Tuple 元组

元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表

元组是不允许更新的,而列表是允许更新的。

tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )

tinytuple = (123, 'john') 

# 输出完整元组

print tuple

('runoob', 786, 2.23, 'john', 70.2)

 # 输出元组的第一个元素

print tuple[0] 

runoob

 # 输出第二个至第四个(不包含)的元素 

print tuple[1:3] 

(786, 2.23)

 # 输出从第三个开始至列表末尾的所有元素

print tuple[2:] 

(2.23, 'john', 70.2)

 # 输出元组两次

print tinytuple * 2 

(123, 'john', 123, 'john')

 # 打印组合的元组

print tuple + tinytuple 

('runoob', 786, 2.23, 'john', 70.2, 123, 'john')

字典 dictionary

列表是有序的对象集合,字典是无序的对象集合。

两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典用"{ }"标识

字典由索引(key)和它对应的值value组成。

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

tinydict = {'name': 'runoob','code':6734, 'dept': 'sales'}

# 输出键为'one' 的值

print dict['one']

This is one

# 输出键为 2 的值

print dict[2]

This is two

# 输出完整的字典

print tinydict

{'dept': 'sales', 'code': 6734, 'name': 'runoob'}

# 输出所有键

print tinydict.keys()

['dept', 'code', 'name']

# 输出所有值

print tinydict.values()

['sales', 6734, 'runoob']

Python数据类型转换

Dictionary -> List

list(f'{23:08b}')

['0', '0', '0', '1', '0', '1', '1', '1']

Dictionary -> Number->List

[int(e) for e in f'{23:08b}']

[0, 0, 0, 1, 0, 1, 1, 1]

remove()

random choose the position of that, remove的位置每次都是从0开始,0、1、2、3,所以如果remove的下一位也是0,它会被顺位到前一位,下一次remove就轮空了

remove() method removes the first matching element

L = [1, 0, 2, 0, 0, 3, 0, 0, 4, 0]

for e in L:

    if e == 0:

        L.remove(e)

[1, 2, 3, 0, 4, 0]

L2 = [1, 0, 2, 0, 0, 3, 0, 0, 0, 4, 0]

for e in list(L2):

        if e == 0:

            L2.remove(e)

L2

[1, 2, 3, 4]

S = {1, 0, 2, 0, 0, 3, 0, 0, 0, 4, 0}

for e in set(S):

    if e == 0:

        S.remove(e)

S

{1, 2, 3, 4}

Map something

把23的二进制数8位的每一位与从0到8的三位二进制数的tuple进行组合,形成一个dictionary里,如果想倒着map,values[n]可以变成-n-1或者7-n,因为[]中的数只是标记values这个列表的位置。

values = [int(e) for e in f'{23:08b}']

D = {}

for n in range(8):

    D[tuple(int(e) for e in f'{n:03b}')] = values[n]

D

{(0, 0, 0): 0, (0, 0, 1): 0, (0, 1, 0): 0, (0, 1, 1): 1, (1, 0, 0): 0, (1, 0, 1): 1, (1, 1, 0): 1, (1, 1, 1): 1}

十进制变三位二进制的新方法

{(n // 4, n % 4 // 2, n % 2): values[7 - n] for n in range(8)}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容