A02_

Python的版本

基本數據類型

與大多數語言一樣,Python有許多基本類型,包括整數,浮點數,布爾值和字符串。這些數據類型的行爲方式與其他編程語言相似。
Numbers(數字類型):代表的是整數和浮點數,它原理與其他語言相同:

# -*- coding: UTF-8 -*-

x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

注意,與許多語言不同,Python沒有一元增量(x+)或遞減(x-)運算符。
Python還有用於複數的內置類型;你可以在這篇文檔中找到所有的詳細信息。
Booleans(布爾類型): Python實現了所有常用的布爾邏輯運算符,但它使用的是英文單詞而不是符號 (&&, ||, etc.):

# -*- coding: UTF-8 -*-

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f)  # Logical OR; prints "True"
print(not t)   # Logical NOT; prints "False"
print(t != f)  # Logical XOR; prints "True"

Strings(字符串類型):Python對字符串有很好的支持:

hello = 'hello'    # String literals can use single quotes
world = "world"    # or double quotes; it does not matter.
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"

String對象有許多有用的方法;例如:

s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))     # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                                # prints "he(ell)(ell)o"
print('  world '.strip())  # Strip leading and trailing whitespace; prints "world"

容器(Containers)
Python包含幾種內置的容器類型:列表、字典、集合和元組。

列表(Lists)
列表其實就是Python中的數組,但是可以它可以動態的調整大小並且可以包含不同類型的元素:

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
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 "[3, 1, 'foo', 'bar']"
x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"

我們將在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))

列表推導式(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]"

字典
字典存儲(鍵,值)對,類似於Java中的Map或Javascript中的對象。你可以像這樣使用過它:

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"

(循環)Loops:迭代詞典中的鍵很容易:

d = {"person":2,'cat':4,'spider':8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal,legs))

運行結果:

A person has 2 legs
A cat has 4 legs
A spider has 8 legs

如果要訪問鍵及其對應的值,請使用items方法:

nums = [0,1,2,3,4]
even_num_to_square = {x : x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)

集合(Sets)
集合是不同元素的無序集合。舉個簡單的例子,請思考下面的代碼:

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
animals.add('fish')       # Add an element to a set
print('fish' in animals)  # Prints "True"
print(len(animals))       # Number of elements in a set; prints "3"
animals.add('cat')        # Adding an element that is already in the set does nothing
print(len(animals))       # Prints "3"
animals.remove('cat')     # Remove an element from a set
print(len(animals))       # Prints "2"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章