python 入门

bool
t, f = True, False
print type(t) # Prints "<type 'bool'>"
 
字符串
hello = 'hello'   # 实在想不出的时候就用hello world
world = "world"
print hello, len(hello) # 字符串长度
 
 
列表,注意,python的容器可以容纳不同的数据类型,[ ] 中括号是列表
xs = [3, 1, 2]   # 建一个列表
print xs, xs[2]
print xs[-1]     # 用-1表示最后一个元素,输出来
 
[3, 1, 2] 2
2
 
xs.append('happy') # 可以用append在尾部添加元素
print xs
[3, 1, 'Hanxiaoyang', 'happy']
 
x = xs.pop()     # 也可以把最后一个元素“弹射”出来
print x, xs
 
happy [3, 1, 'Hanxiaoyang']
 
 
列表切片
 
nums = range(5)    # 0-4
print nums         # 输出 "[0, 1, 2, 3, 4]"
print nums[2:4]    # 下标2到4(不包括)的元素,注意下标从0开始
print nums[2:]     # 下标2到结尾的元素; prints "[2, 3, 4]"
print nums[:2]     # 直到下标2的元素; prints "[0, 1]"
print nums[:]      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print nums[:-1]    # 直到倒数第一个元素; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # 也可以直接这么赋值
print nums         # Prints "[0, 1, 8, 8, 4]"
 
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 8, 9, 4]
 
 
animals = ['喵星人', '汪星人', '火星人']
for animal in animals:
    print animal
 
喵星人
汪星人
火星人
 
又要输出元素,又要输出下标怎么办,用 enumerate 函数:
animals = ['喵星人', '汪星人', '火星人']
for idx, animal in enumerate(animals):
    print '#%d: %s' % (idx + 1, animal)
 
#1: 喵星人
#2: 汪星人
#3: 火星人
 
 
List comprehensions:
 
如果对list里面的元素都做一样的操作,然后生成一个list,用它最快了,这绝对会成为你最爱的python操作之一:
 
# 求一个list里面的元素的平方,然后输出,很out的for循环写法
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print squares
[0, 1, 4, 9, 16]
 
nums = [0, 1, 2, 3, 4]
# 对每个x完成一个操作以后返回来,组成新的list
squares = [x ** 2 for x in nums]
print squares
[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
 
 
字典 { }是字典
 
d = {'cat': 'cute', 'dog': 'furry'}  # 建立字典
print d['cat']       # 根据key取value
print 'cat' in d     # 查一个元素是否在字典中
cute
True
 
d['fish'] = 'wet'    # 设定键值对
print d['fish']      # 这时候肯定是输出修改后的内容
wet
 
print d['monkey']  # 不是d的键,肯定输不出东西
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-f37735e1a686> in <module>()
----> 1 print d['monkey']  # 不是d的键,肯定输不出东西

KeyError: 'monkey'
 
print d.get('monkey', 'N/A')  # 可以默认输出'N/A'(取不到key对应的value值的时候)
print d.get('fish', 'N/A')
N/A
N/A
 
del d['fish']        # 删除字典中的键值对
print d.get('fish', 'N/A') # 这会儿就没有了
 
N/A
 
你可以这样循环python字典取出你想要的内容:
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 spider has 8 legs
A cat has 4 legs
 
用iteritems函数可以同时取出键值对:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
    print 'A %s has %d legs' % (animal, legs)
 
A person has 2 legs
A spider has 8 legs
A cat has 4 legs
 
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
even_list = [ x ** 2 for x in nums if x % 2 == 0]
print even_list
{0: 0, 2: 4, 4: 16}
[0, 4, 16]
 
Set:不包含相同的元素,没有value,只有key,用{}表示
 
元组(tuple):元组可以作为字典的key或者set的元素出现,但是list不可以作为字典的key或者set的元素。
 
d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print type(t)
print d[t]       
print d[(1, 2)]
<type 'tuple'>
5
1
 
 
函数
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'
 
for x in [-1, 0, 1]:
    print sign(x)
negative
zero
positive
 
函数名字后面接的括号里,可以有多个参数,你自己可以试试:
def hello(name, loud=False):
    if loud:
        print 'HELLO, %s' % name.upper()
    else:
        print 'Hello, %s!' % name
 
hello('Bob')
hello('Fred', loud=True)
Hello, Bob!
HELLO, FRED
 
class Greeter:
 
    # 构造函数
    def __init__(self, name):
        self.name = name  # Create an instance variable
 
    # 类的成员函数
    def greet(self, loud=False):
        if loud:
            print 'HELLO, %s!' % self.name.upper()
        else:
            print 'Hello, %s' % self.name
 
def hello(name, loud=False):
    if loud:
        print 'HELLO, %s' % name.upper()
    else:
        print 'Hello, %s!' % name
 
 
g = Greeter('Fred')  # 构造一个类
g.greet()            # 调用函数; prints "Hello, Fred"
g.greet(loud=True)   # 调用函数; prints "HELLO, FRED!"
g.greet(True)
 
Hello, Fred
HELLO, FRED!
HELLO, FRED!
 
 
 
 
原文地址:https://www.cnblogs.com/diegodu/p/5822157.html