Getting started with python in ten minutes

1. Variables, numbers, sequences, tuples, maps (dictionaries) and sets

Source code download

1.1 Variables

# 定义美元
dollar = 100
# 定义汇率
exchange = 6.4696

print(dollar, exchange)
# 输出结果:100 6.4696

 1.2 Numbers, strings

#定义数字
bandwidth = 100
ratio = 8

print(bandwidth/ratio)

#定义字符串
a = 'abcd'
print(a)
 1.2.1 String interception
#字符串截取,截取3位
a = 'abcdefg'
b = a[0:3]
print(b)
1.2.2 The length of the string len()
# len()函数返回字符串的长度:
a = 'abcd'
print(len(a))
# 输出:4
 1.2.3 Remove leading and trailing whitespace characters with strip()
#strip() 方法删除开头和结尾的空白字符:
a = '  hello world'
print(a.strip())
#输出:hello world
1.2.4 lower() returns a lowercase string:
#lower() 返回小写的字符串:
a = "Hello, World!"
print(a.lower())
#输出:hello, world!
 1.2.5 The upper() method returns an uppercase string:
#upper() 方法返回大写的字符串:
a = "Hello, World!"
print(a.upper())
#输出:HELLO, WORLD!
1.2.6 replace() Replace a string with another string:
#replace() 用另一段字符串来替换字符串:
a = "Hello, World!"
print(a.replace("World", "Kitty"))
#输出:Hello, Kitty!
1.2.7 The split() method splits a string into substrings when an instance of the delimiter is found: 
#split() 方法在找到分隔符的实例时将字符串拆分为子字符串:
a = "Hello, World!"
print(a.split(",")) 
# 输出:['Hello', ' World!']
1.2.8 To check whether a specific phrase or character exists in a string, we can use the in or not in keywords 
#检查字符串中是否存在特定短语或字符,我们可以使用 in 或 not in 关键字
txt = "China is a great country"
x = "ina" in txt
print(x)
#输出: True
 1.2.9 find() search
#find() 查找
txt = "Hello, welcome to my world."
print(txt.find("q"))
#输出:-1

1.3 Type conversion

Implicit class conversion

Implicit type conversion, also known as automatic type conversion, occurs when Python automatically converts one data type to another. This happens when a value of one type is assigned to a variable of another type.

For example, if we assign a float to an integer variable, Python will implicitly cast the float to an integer:

x = 10.5
y = int(x)
print(y)

# 输出:10

In this example, when the floating point number 10.5 is assigned to the integer variable y, it is implicitly converted to the integer 10

explicit type conversion

Explicit type conversion, also known as manual type conversion, occurs when the programmer uses type conversion functions to explicitly convert a value from one type to another type.

For example, if we want to convert an integer to a floating point number, we can use the float() function:

#显式类型转换
x = 10
y = float(x)
print(y)

# 输出:10.0

 In this example, when the floating point number 10.5 is assigned to the integer variable y, it is implicitly converted to the integer 10

String conversion str()
# 将整数转换为字符串
x = 10
y = str(x)
print(y)

# 将一个浮点数转换为一个字符串
x = 10.5
y = str(x)
print(y)

1.4 Sequence List

1.4.1 Define sequence
#定义序列
a_list = ['abc', 'xyz']
1.4.2 Sequence addition and deletion
#添加
a_list = ['abc', 'xyz']
a_list.append('X')
print (a_list)
# 输出:['abc', 'xyz', 'X']

# 删除
a_list.remove('xyz')
print(a_list)
#输出:['abc', 'X']
1.4.3 Determine whether an element is an element of a sequence
#判断某个元素是否为某个序列的元素
s1=[1,2,3,4,5,6]
print(3 in s1)
#输出:True
 1.4.4 Calculate the length, maximum and minimum values ​​of the sequence

The length of the sequence: len()

Maximum value of the sequence: max()

Minimum value of sequence: min()

#计算序列的长度、最大值和最小值
s1=[15,55,56,2,53,43,96,61]
print("序列为:",s1[:])
print("序列的长度为:",len(s1))
print("序列的最大值为:",max(s1))
print("序列的最小值为:",min(s1))

#输出:序列为: [15, 55, 56, 2, 53, 43, 96, 61]
#序列的长度为: 8
#序列的最大值为: 96
#序列的最小值为: 2
1.4.5 Sequence sorting 

Python lists have a built-in list.sort() method that can modify the list directly. There is also a sorted() built-in function, which constructs a new sorted list from an iterable object.

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

The meaning of the parameters is:

cmp -- optional parameter, if this parameter is specified, the method of this parameter will be used for sorting.

key - is mainly used for comparison elements, with only one parameter. The parameters of the specific function are taken from the iterable object, and an element in the iterable object is specified for sorting.

reverse -- sorting rule, reverse = True for descending order, reverse = False for ascending order (default).
 

#序列排序 
s1=[15,7,56,2,53,43,96,61]
s1.sort()
print(s1)
#输出:[2, 7, 15, 43, 53, 56, 61, 96]

#降序
s1=[15,7,56,2,53,43,96,61]
s1.sort(reverse=True)
print(s1)

 sorted() function:

sorted(iterable, cmp=None, key=None, reverse=False)

in:

iterable – Iterable object.

cmp - Comparison function. This has two parameters. The values ​​of the parameters are taken from the iterable object. The rules that this function must follow are: if it is greater, it returns 1, if it is less, it returns -1, and if it is equal, it returns 0.

key - is mainly used for comparison elements, with only one parameter. The parameters of the specific function are taken from the iterable object, and an element in the iterable object is specified for sorting.

reverse -- sorting rule, reverse = True for descending order, reverse = False for ascending order (default).

Similarly, the list can be sorted using the sorted() function, for example:

# sorted()函数:
#sorted(iterable, cmp=None, key=None, reverse=False)
list=[1,7,4,5,3]
print(sorted(list))
#输出:[1, 3, 4, 5, 7]

#降序
list=[1,7,4,5,3]
print(sorted(list, reverse=True))
#[7, 5, 4, 3, 1]
1.4.6 Filter sequence elements

Use if statements to filter sequence elements

#使用if语句来过滤序列元素
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
# 输出[2, 4, 6]

filter() function


#过滤序列元素filter()
#定义过滤函数
def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
# 输出[2, 4, 6]

 lambda expression

#lambda 表达式
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x%2 == 0, numbers))
print(even_numbers)
# 输出[2, 4, 6]

 1.5 tuple

Brief description

What is a tuple? A simple understanding is to store a bunch of data in a container, but this container has a characteristic, that is, it is very stubborn. In a sense, its function is similar to that of a 一旦定义了之后就不可改变list 元组就是不可以改变的列表, and it can also be sliced, modified, etc. operate.

1.5.1 Define tuples
#一维元组
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座',
           u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
#二维元组
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
              (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))

 在Python中任意无符号的对象,以逗号隔开,默认为元组, the sample code is as follows:

a = 1,3,4,5
print(type(a), a)
#输出:<class 'tuple'> (1, 3, 4, 5)
1.5.2 Accessing tuple elements
#访问元组元素
my_tuple = (1,2,3,4,5,6)
#访问第二个元素
print(my_tuple[1])
#输出:2
#访问第2个到第4个元素
print(my_tuple[1:4])
#输出:(2, 3, 4)
1.5.3 Operations on tuples
#元组的相关运算符
a = (1,2,3,4)
b = (5,6,7,8)
#元组的拼接
print(a+b)
#输出:(1, 2, 3, 4, 5, 6, 7, 8)
#元组的重复
print(a*2)
#输出:(1, 2, 3, 4, 1, 2, 3, 4)
1.5.4 Convert the corresponding data type into a tuple
#将对应数据类型转换成元组
#将列表转成元组
v_list = [1,2,3,4,5,6]
v_tuple = tuple(v_list)
print(type(v_tuple), v_tuple)
#输出:<class 'tuple'> (1, 2, 3, 4, 5, 6)
#将字符串转成元组
a = "happy"
tuple_a = tuple(a)
print(type(tuple_a), tuple_a)
#输出:<class 'tuple'> ('h', 'a', 'p', 'p', 'y')
 1.5.5 Tuple-based applet to calculate zodiac sign based on date of birth
#定义星座
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座',
           u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
#星座对应日期
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
              (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
# 用户输入月份和日期
int_month = int(input('请输入月份:'))
int_day = int(input('请输入日期'))

n = 0
while zodiac_days[n] < (int_month,int_day):
    if int_month == 12 and int_day >23:
        break
    n += 1

print(zodiac_name[n])

 1.6 Mapping (dictionary)

Python dictionary is a mutable container model and can store any type of object, such as strings, numbers, tuples and other container models.

Each key=>value pair in the dictionary is separated by colon:. Each pair is separated by comma. The entire dictionary is included in curly braces {}. The format is as follows:

d = {key1 : value1, key2 : value2 }

1.6.1 Creation of dictionary
#字典的创建
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
f = dict({'one': 1, 'three': 3}, two=2)
print(a, b)
print(a == b, a == c, a == d, a == e, a == f)
#输出:{'one': 1, 'two': 2, 'three': 3} {'one': 1, 'two': 2, 'three': 3} {'one': 1, 'three': 3, 'two': 2}
#True True True True True
1.6.2 Dictionary methods

fromkeys()

Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and value is the initial value corresponding to all keys in the dictionary.

#fromkeys()
#创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
seq = ('Google', 'Baidu', 'Taobao')
dict1 = dict.fromkeys(seq)
print(dict1)
#输出:{'Google': None, 'Baidu': None, 'Taobao': None}
dict2 = dict.fromkeys(seq, 1)
print(dict2)
#输出:{'Google': 1, 'Baidu': 1, 'Taobao': 1}

 clear() clear

# clear() 清空
b = {'one': 1, 'two': 2, 'three': 3}
b.clear()
print(b)

 get() value

# get() 取值
b = {'one': 1, 'two': 2, 'three': 3}
print(b.get("one"))
print(b.get("four"))
#输出:1
# None

 keys() returns all the keys of a dictionary as a list

#  keys() 以列表返回一个字典所有的键
dict1 = {'name' : 'Alice', 'age' : 23, 'address' : 'Hangzhou'}
print(dict1.keys())
#输出:dict_keys(['name', 'age', 'address'])
#转换成列表['name', 'age', 'address']
li = list(dict1.keys())
print(li)
#输出:['name', 'age', 'address']

 values() returns the values ​​corresponding to all keys in the dictionary

#values() 返回字典中所有键对应的值
dict1 = {'name': 'Alice', 'age': 23, 'address': 'Hangzhou'}
print(dict1.values())
#输出:dict_values(['Alice', 23, 'Hangzhou'])
#转换成列表
li = list(dict1.keys())
print(li)
#输出:['name', 'age', 'address']

 items() list returns a traversable array of (key, value) tuples

# items() 列表返回可遍历的(键, 值) 元组数组
dict1 = {'name': 'Alice', 'age': 23, 'address': 'Hangzhou'}
item = dict1.items()
print(item)
#输出:dict_items([('name', 'Alice'), ('age', 23), ('address', 'Hangzhou')])

 pop() delete

# pop 删除
dict1 = {'name':'Alice','age':23,'address':'Hangzhou'}
dict1.pop('age')
print(dict1)
#输出:{'name': 'Alice', 'address': 'Hangzhou'}

 update() updates the key-value pairs of the dictionary and updates the key-value pairs in the dictionary in the parameter to the dictionary. This method has no return value.

#  update() 更新字典的键-值对,将参数中字典中的键值对更新到字典中,此方法无返回值
dict1 = {'name': 'Alice', 'age': 23, 'address': 'Hangzhou'}
dict1.update({'age': 80})
print(dict1)
#输出:{'name': 'Alice', 'age': 80, 'address': 'Hangzhou'}

Other support

#其他支持
a = {'name': 'Alice', 'age': 23, 'address': 'Hangzhou'}
# len(d)
print(len(a))
# d[key] 返回 d 中以 key 为键的项。如果映射中不存在 key 则会引发 KeyError。
print(a['name'])
#d[key] = value 将 d[key] 设为 value
a['name'] = '小明'
print(a)
#输出: {'name': '小明', 'age': 23, 'address': 'Hangzhou'}
#del d[key] 删除key 如果映射中不存在 key 则会引发 KeyError。
del a['address']
print(a)
#输出:{'name': '小明', 'age': 23}
#  key in d 如果 d 中存在键 key 则返回 True,否则返回 False
print('name' in a)
#输出:True
# iter(d) 返回以字典的键为元素的迭代器。这是 iter(d.keys()) 的快捷方式。
d = iter(a)
print(list[iter(a)])

 1.7 Set

Sets are unordered and unindexed collections. In Python, sets are written using curly braces.

#集合是无序和无索引的集合。在 Python 中,集合用花括号编写。
thisset = {"apple", "banana", "cherry"}
print(thisset)
#输出:{'cherry', 'apple', 'banana'}
1.7.1 Collection traversal
#遍历集合,并打印值:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)
#输出:apple cherry banana
1.7.2 Check whether an object exists in the collection
#检查 集合中是否存在某对象
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)
#输出:True
1.7.3 Adding add() and update() to the collection
#使用 add() 方法向 set 添加项目:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
#输出:{'orange', 'apple', 'cherry', 'banana'}

#使用 update() 方法将多个项添加到集合中:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
#输出:{'cherry', 'mango', 'grapes', 'orange', 'banana', 'apple'}
1.7.4 Delete a project  remove() or  discard() method
#集合删除项目 remove() 或 discard() 方法
#如果要删除的项目不存在,则 remove() 将引发错误。
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
#输出: {'cherry', 'apple'}

#使用 discard() 方法来删除
#如果要删除的项目不存在,则 discard() 不会引发错误
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
#输出:{'apple', 'cherry'}
 1.7.5 Merging collections

In Python, there are several ways to join two or more collections.

You can use the union() method to return a new collection containing all the items in both collections, or you can use the update() method to insert all the items in one collection into the other:

#在 Python 中,有几种方法可以连接两个或多个集合。
#您可以使用 union() 方法返回包含两个集合中所有项目的新集合,也可以使用 update() 方法将一个集合中的所有项目插入另一个集合中:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
#输出:{1, 2, 3, 'b', 'a', 'c'}

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
#输出:{'c', 1, 2, 3, 'a', 'b'}

If this document is not detailed enough, you can refer to learn python in ten minutes_bilibili_bilibili​

Guess you like

Origin blog.csdn.net/kan_Feng/article/details/131811845