Python basic comprehensive application crash 2

In order to make a comparison and strengthen the comprehensive application, first import two libraries: numpy and random

If you don't run the terminal on the right under pycharm, enter pip install numpy

import numpy as np
import random

1. The difference between list and array, and their conversion

a_0 = np.array([1, 2, 3, 4])  # 数组
print(a_0, "\n长度为:", len(a_0))
print(list(a_0))
a_list = a_0.tolist()
print(a_list)

[1 2 3 4] 
The length is: 4
[1, 2, 3, 4]
[1, 2, 3, 4]

There are no commas between the arrays, and there are commas in the list. There are two ways to convert the array to a list: list(a_0), a_list = a_0.tolist(),

You can use type(), and len() to view the types and lengths of the two of them, both of which are list list types, and the length is 4

On this basis, multidimensional arrays and conversions can be established : such as


a_0 = np.array([[[1, 2, 3, 4]]])  # 三维数组
print(a_0, "\n长度为:", len(a_0))
print(list(a_0))
a_list = a_0.tolist()
print(a_list)
[[[1 2 3 4]]] 
Length is: 1
[array([[1, 2, 3, 4]])]
[[[1, 2, 3, 4]]]

You can see that the list converted by list() method has changed, and it cannot be changed by applying list(list()), so it is recommended to use tolist conversion

2. Array and output

a0 = np.arange(1, 10)  #
a00 = np.random.randint(1, 5)
print(a0, a00, a0[0:], [a00], [a00][0], [[a00][0]])
print(len(a0)+len(f' '))  # 9+1
print(list(a0[1:3]))
print(list(a0[0:5])[4])

[1 2 3 4 5 6 7 8 9] 3 [1 2 3 4 5 6 7 8 9] [3] 3 [3]
10
[2, 3]
5

Among them, you can see that both arrays and lists can output values ​​​​with subscript indexes, and slices can be used, such as a0[0:] is the slice of the array, [0:], 0 is the starting index, and the value is not followed by: cut to the end

3. Addition, deletion and modification of the list

city = ['北京', '上海', '曹县', '广州']
print(f'city列表的元素个数:{len(city)}')
# 列表元素的添加 列表名.append(添加的元素) 到结尾
city.append('威海')
# 列表的插入 列表名.insert(元素的索引,插入的元素
city.insert(2, '山东')
print(city)
# 列表元素的删除  列表名.pop(被删除的元素下表)不写索引删最后一个
city.pop(2)
print(city)
# 列表元素的移除  列表名.remove(被删除的元素)
# city.remove('山东')
# 列表元素的修改 列表名[索引] = '新值'
city[2] = '深圳'
print(city)
# extend() 向列表末尾添加多个元素
city.extend(['安徽', '湖北'])
print(city)

The number of elements in the city list: 4
['Beijing', 'Shanghai', 'Shandong', 'Cao County', 'Guangzhou', 'Weihai'] [
'Beijing', 'Shanghai', 'Cao County', 'Guangzhou', 'Weihai']
['Beijing', 'Shanghai', 'Shenzhen', 'Guangzhou', 'Weihai']
['Beijing', 'Shanghai', 'Shenzhen', 'Guangzhou', 'Weihai', 'Anhui', 'Hubei']

element swap

# 元素互换
city[3], city[4] = city[4], city[3]
print(city)

['Beijing', 'Shanghai', 'Shenzhen', 'Weihai', 'Guangzhou', 'Anhui', 'Hubei']

list2 = [city[1], city[2:4]]
list3 = []
for i in range(-2, 1):
    list3.append(city[i])
print(list3)
del list3[::2]
print(list3)
print((list2+list3)*2)  # +拼接 *自我复制
print(dir(list))

['Anhui', 'Hubei', 'Beijing']
['Hubei']
['Shanghai', ['Shenzhen', 'Weihai'], 'Hubei', 'Shanghai', ['Shenzhen', 'Weihai'] , 'Hubei']
['__add__', '__class__', '__class_getitem__', '__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__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

# random中的 choice() 从非空序列(列表)随机获取一个元素,列表包含另一个列表,应使用两次
eggs = ['鸡蛋', '铁蛋', ['天鹅蛋', '企鹅蛋', '傻蛋'], '鸭蛋']
print(eggs[2][2])
print(r.choice(eggs))
print(r.choice(r.choice(eggs)))
# del 可以删除列表中某个(些)元素.还可以删除整个变量 如 del eggs pirint(eggs)  
# Traceback (most recent call last): name'eggs' is not defined
del eggs[0]
print(eggs)

Stupid
egg duck egg
swan egg
['iron egg', ['swan egg', 'penguin egg', 'stupid egg'], 'duck egg']

4. List index

list4 = [1, 1, 1, 1, 15, 6, 8, 1]
# count()统计某个元素在列表出现的次数
print(list4.count(1))
# index()返回某个元素在列表第一次出现的索引值
print(list4.index(1))
# 用index方法限定查找范围:
start = list4.index(1)+1
stop = len(list4)
print(list4.index(1, start, stop))

5
0
1

5. List sorting

# reverse()整个列表翻转:
list4.reverse()
print(list4)
# sort()对元素进行排序,可以搭配reverse(),或设置参数,默认时sort(reverse=false)
list4.sort()
print(list4)

7. Tuple:

# 元组 只可以被访问不能被修改,可以使用切片
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1)
# 元组的标识符号  (逗号)
tuple2 = (520,)
print(type(tuple2))
# 更新和删除元组
x_men = ('金刚狼', "x教授", "暴风女", "火凤凰", "镭射眼")
print(id(x_men))
x_men = (x_men[0], "o")+x_men[2:]
print(x_men, id(x_men))

(1, 2, 3, 4, 5, 6, 7, 8)
<class 'tuple'>
2651289514480
('Wolverine', 'o', 'Storm', 'Phoenix', 'Cyclops') 2651290700912

8. String built-in methods

str1 = '-we can figure out-'
print(str1.capitalize())  # 将字符串第一个字符改为大小, 其它为小写
print(str1.casefold())   # 所有字符改为小写
print(str1.center(26, "|"))    # center(width[,fillchar]) 当字符>width,字符串不变,<width,居中,并填充空格 fillchar指填充的字符,默认是空格
print(str1.count(' ', 5, len(str1)))   # count(SUB,START,EDN)  返回sub参数在字符串里出现的次数;
print(str1.encode(encoding='utf-8'))    # 以encoding参数指定的编码格式对字符串进行编码
print(str1.endswith('o', 1, len(str1)-3))        # 检查字符串是否以sub参数结束,如果是返回true,否则返回false
print(str1.find('c'))                    # find(sub,start,end) 检查sub参数是否包含在字符串中,有返回第一个出现位置的索引值,否则返回1
print(str1.index('c'))   # 与find 方法一样,不过该方法找不到抛出ValueError异常
print(str1.isalnum())     # 如果字符串仅由字母或数字构成返回true 否则 false
print(str1.isalpha())       # 如果字符串仅由字母构成返回true 否则 false
print(str1.isdigit())    # 如果字符串仅由数字构成返回true 否则 false
print(str1.islower())     # 字符串仅由小写字母构成返回true   对应的isupper
print(str1.isspace())       # 仅由空格
print(str1.join(c))         # str1.join(iterable)以字符串作为分隔符,插入到 iterable 参数迭代出来的所有字符串之间 若包含非字符串值抛出异常
print(str1.split())     # split(sep=None,maxsplit=-1)以空白字符作为分割符对字符串进行分割  sep参数指定分隔符,默认是空白字符 maxsplit是最大分割次数,默认不限
print(str1.strip())    # strip(chars)删除字符串前后所有空白字符 chars指定待删除字符集
# 字符串修改的方法并不是修改原字符串,而是返回字符串的拷贝

-we can figure out-
-we can figure out-
|||-we can figure out-||||
2
b'-we can figure out-'
True
4
4
False
False
False
True
False
1
['-we', 'can', 'figure', 'out-']
-we can figure out-

countries = ['中国', '俄罗斯', '美国', '日本', '韩国']
print('-'.join(countries))
print('%#x' % 100)
# 字符串迭代存放列表中
a = list('贴贴,我说的,(,,´•ω•)ノ"(´っω•`。)')
cute_cat = tuple("臭卷宝")
print(a, "\n", max(cute_cat))

China-Russia-America-Japan-Korea
0x64
['post', 'post', ',', 'I', 'say', 'of', ',', '(', ',', ',' , '´', '•', 'ω', '•', ')', 'ノ', '"', '(', '´', 'っ', 'ω', '•', ' '', '.', ')'] 
 smelly

0x means hexadecimal

9. Pack and unpack

# 默认参数def a(name=none,single = true,sex='男')
# 收集参数
def test(*params):  # *在参数里的作用:'打包',多个参数打包成元组形式存储 实参*为解包
    print("有%d个参数" % len(params))
    print('第二个参数是:', params[1])
    return params


p = test('阿巴巴巴', '阿巴巴', '哦')
print(p, *p)

There are 3 parameters
The second parameter is: Ababa
('Abababa', 'Ababa', 'oh') Abababaababaoh

Guess you like

Origin blog.csdn.net/qq_53521409/article/details/126673487