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!
 
 
 
 

最新文章

  1. android nfc中MifareClassic格式的读写
  2. Android自动接听&amp;挂断电话(包含怎么应对4.1以上版本的权限检
  3. XACML-条件评估(Condition evaluation),规则评估(Rule evaluation),策略评估(Policy evaluation),策略集评估(PolicySet evaluation)
  4. 【转】Android Studio系列教程一--下载与安装
  5. MYSQL5.5和5.6参数的差异
  6. muduo简化(1):Reactor的关键结构
  7. Linux如何创建一个进程
  8. DOM备忘录
  9. postgresql 使用pg_restore时显示role &quot;root&quot; does not exist的解决办法
  10. 小白在 Eclipse如何避免启动时自动building workspace和validating
  11. sklearn交叉验证-【老鱼学sklearn】
  12. python3 第三十二章 - 标准库概览
  13. 【原创】Python第二章——行与缩进
  14. poj1061-青蛙的约会-(贝祖定理+扩展欧几里得定理+同余定理)
  15. Android RIL结构分析与移植
  16. [USACO08NOV]Cheering up the Cow
  17. Python 使用正则表达式匹配电话号码
  18. Jquery中动态生成的元素没有点击事件或者只有一次点击事件
  19. 【Raspberry Pi】 小问题汇总
  20. 以太坊(二)安装Solidity编译器

热门文章

  1. 修改Tomcat可支持get形式url长度
  2. 添加web引用和添加服务引用有什么区别?
  3. 从客户端中检测到有潜在危险的request.form值
  4. 利用opencv3中的kmeans实现抠图功能
  5. Android 编程下 Touch 事件的分发和消费机制
  6. LeetCode-Count Univalue Subtrees
  7. 移动统计工具Flurry
  8. C++ VS2010 声明没有存储类或类型说明符
  9. html5新增选择器
  10. Windows Phone 开发——相机功能开发