从零开始学习python语言

本文介绍了Python的基础知识,包括快速排序算法的实现、基本数据类型的使用、布尔型操作、字符串处理、列表与字典的操作方法等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python实现的经典的quicksort算法例子:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

print ( quicksort ([3,6,8,10,1,2,1]) )

基本数据类型

```python
x =3
print ( type (x) ) #<class 'int'>
print(x) #3
print(x+1) #4
print(x-1) #2
print(x*2) #6
print(x**2) #9
x+=1
print(x) #4
x*=2
print(x) #8
y=2.5
print ( type (y) ) #<class 'float'>
print(y,y+1,y*2,y**2) #2.5 3.5 5.0 6.25

需要注意的是,Python中没有 x++ 和 x-- 的操作符。

Python也有内置的长整型和复杂数字类型,具体细节可以查看文档。

布尔型:Python实现了所有的布尔逻辑,但用的是英语,而不是我们习惯的操作符(比如&&和||等)。

t = True
f = False
print (type(t))  # <class 'bool'>
print (t and f) # False
print (t or f)  #  True
print (not t)   #  False
print (t != f)  # True

字符串:Python对字符串的支持非常棒。

hello ="hello"
world ="world"
print(hello)
print(len(hello))
hw=hello+' '+world
print(hw)
hw2= '%s %s %d' % (hello, world, 12)
print(hw2)

列表Lists
列表就是Python中的数组,但是列表长度可变,且能包含不同类型元素。

xs = [3, 1, 2]   # Create a list
print (xs,xs[0],xs[2])  # Prints "[3, 1, 2] 2"
print (xs[-1])     # Negative indices count from the end of the list; prints "2"
print (xs[-2])
print (xs[-3])

xs[2] = 'foo'    # Lists can contain elements of different types
print (xs)         # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print (xs)         # Prints

x = xs.pop()     # Remove and return the last element of the list
print (x, xs)      # Prints "bar [3, 1, 'foo']"

切片Slicing:为了一次性地获取列表中的元素,Python提供了一种简洁的语法,这就是切片。

nums = list(range(5))       # range is a built-in function that creates a list of integers
print (nums)         # Prints "[0, 1, 2, 3, 4]"
print (nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print (nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print (nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print (nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print (nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9]   # Assign a new sublist to a slice
print (nums)         # Prints "[0, 1, 8, 9, 4]"

在Numpy数组的内容中,我们会再次看到切片语法。

循环Loops:我们可以这样遍历列表中的每一个元素:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print (animal)
# Prints "cat", "dog", "monkey", each on its own line.

如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print (('#%d: %s' % (idx + 1, animal)))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

列表推导List comprehensions:在编程的时候,我们常常想要将一种数据类型转换为另一种。下面是一个简单例子,将列表中的每个元素变成它的平方。

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print (squares)   # Prints [0, 1, 4, 9, 16]

使用列表推导,你就可以让代码简化很多:

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print (squares)   # Prints [0, 1, 4, 9, 16]

列表推导还可以包含条件:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x%2 ==0]
print (even_squares)   # Prints [0, 4, 16]

字典Dictionaries
字典用来储存(键, 值)对,这和Java中的Map差不多。你可以这样使用它:

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print (d['cat'])       # Get an entry from a dictionary; prints "cute"
print ('cat' in d)     # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet'    # Set an entry in a dictionary
print (d['fish'])      # Prints "wet"
# print d['monkey']  # KeyError: 'monkey' not a key of d
print (d.get('monkey', 'N/A') ) # Get an element with a default; prints "N/A"
print (d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
del d['fish']        # Remove an element from a dictionary
print (d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值