python入门教程、基本类型的操作及相互转换

http://blog.csdn.net/pipisorry/article/details/39234557

python入门教程

[慕课网Python教程]

[简明Python教程]

[Python基本语法[二],python入门到精通[四]]

[python有哪些好的学习资料或者博客?]

[为什么Python中没有Switch/Case语句?]

[StarterLearningPython]

[Python 初学者的最佳学习资源]

[我是如何开始学Python的]

Python中的“真值”

在Python和Django模板系统中,以下这些对象相当于布尔值的False

  • 空列表([] )

  • 空元组(() )

  • 空字典({} )

  • 空字符串('' )

  • 零值(0 )

  • 特殊对象None

  • 对象False(很明显)

Note:

1. 你也可以在自定义的对象里定义他们的布尔值属性(python的高级用法)。

2. 除以上几点以外的所有东西都视为`` True``

python中的int类型

python最大整数

它是由Python的正整数类型所支持的最大整数。

python的最大整数sys.maxsize(py3)   sys.maxint(py2)[py3中无定义]

最小整数:-sys.maxsize+1     -sys.maxint+1

python最大浮点数

sys.float_info:
>>> import sys
>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2
250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil
on=2.2204460492503131e-16, radix=2, rounds=1)

>>> sys.float_info.max
1.7976931348623157e+308

如果这还不够大,总是有正无穷大:
>>> infinity = float("inf")
>>> infinity
inf
>>> infinity / 10000
inf
该long类型有无限的精度,所以只受限于你的内存大小。

[maximum float in python]

[python精度问题]

python for循环高级用法

在分支语句中使用else子句在一些常见的编程语言中的用法基本相同,类似于提供了一条默认的执行路径,配合if等条件判断语句使用,相比其它的编程语言(c#, java, js等)在python中,else有一些特殊的用法,配合for, while等循环语句使用,甚至还能配合异常处理try except语句进行使用,能够让我们的代码更加的简洁。

配合for/while循环语句使用
在for循环语句的后面紧接着else子句,在循环正常结束的时候(非return或者break等提前退出的情况下),else子句的逻辑就会被执行到。先来看一个例子:
def print_prime(n):
    for i in xrange(2, n):
        # found = True
        for j in xrange(2, i):
            if i % j == 0:
                 # found = False 
                break
        else:
            print "{} it's a prime number".format(i)
        # if found:
                  # print "{} it's a prime number".format(i)


print_prime(7)


2 it's a prime number
3 it's a prime number
5 it's a prime number
一个简单打印素数的例子,判断某个数字是否是素数的时候需要遍历比它自己小的整数,任何一个满足整除的情况则判断结束,否则打印这是一个素数的info,有了else的加持,整个例子的逻辑相当的“self-expressive”,如同伪代码一般的好理解而且相比在判断整除的时候设置标志值然后在函数的结尾处判断标志值决定是否打印数字时素数的消息,代码更简洁没有那么多要描述如何做的“过程式”准备工作。
大家可以把例子中的被注释代码运行对比下效果。

[配合 try except错误控制使用]

[善用python的else子句]
皮皮Blog



python列表操作

python列表的插入、抛出、拆箱操作

list的插入操作是调用函数listinsert来实现的。

该函数的流程如下:

1、解析参数。

2、调用静态函数ins1进行插入操作。

list的插入操作对索引值的处理在函数ins1中进行,相关处理过程如下:

1、将列表的条目数赋值给n;
2、如果索引值小于0,则将索引值增加n;如果仍小于0,则将索引值赋值为0;
3、如果索引值大于n,则将索引值赋值为n。

抛出操作当条目索引为负数时的处理

list的抛出操作是将指定索引位置的条目从列表中删除并且返回该条目的值。list的抛出操作是调用函数listpop来实现的。

对索引值index的相关处理过程如下:

1、如果index小于0,则将index增加列表本身的条目数;

2、如果index仍小于0或大于列表条目数,则输出错误信息提示索引值超出范围。

源码中将操作位置初始化为-1,所以如果没有指定抛出位置,则默认抛出最后一个条目。

拆箱

>>> a, b, c  =  [ 1 , 2 , 3 ]
>>> a, b, c
( 1 , 2 , 3 )
>>> a, b, c  =  ( 2 * i + 1 for i in range ( 3 ))
>>> a, b, c
( 1 , 3 , 5 )
>>> a, (b, c), d = [ 1 , ( 2 , 3 ), 4 ]
>>> a
1
>>> b
2
>>> c
3
>>> d
4
扩展的拆箱(Python 3支持)

>>> a,  * b, c = [ 1 , 2 , 3 , 4 , 5 ]
>>> a
1
>>> b
[ 2 , 3 , 4 ]
>>> c
5


python列表查找和索引

List slices with step (a[start:end:step])带步长列表切片

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2]
[0, 2, 4, 6, 8, 10]

List slice assignment列表切片赋值

>>> a = [1, 2, 3, 4, 5]
>>> a[2:3] = [0, 0]
>>> a
[1, 2, 0, 0, 4, 5]
>>> a[1:1] = [8, 9]
>>> a
[1, 8, 9, 2, 0, 0, 4, 5]
>>> a[1:-1] = []
>>> a
[1, 5]

python列表取倒数n个数

a = [1,2,3,4,5,6]
print(a[-3:])

切片命名(slice(start, end, step))

>>> a  = [ 0 , 1 , 2 , 3 , 4 , 5 ]
>>> LASTTHREE  =  slice ( - 3 , None )
>>> LASTTHREE
slice ( - 3 , None , None )
>>> a[LASTTHREE]
[ 3 , 4 , 5 ]

python列表查找某个元素

1. (推荐,不用搜索列表两次,更快)

try:
    k = l.index(4)    #index查找不存在的元素会出异常
except:
    k = 3
2. 
if 4 not in l:
    k = 3
else:
    k = l.index(4)

一个for循环中每次迭代输出两个列表对应的元素及对应的索引号

users = [1,2,3]
items = [4,5,6]
for index, (user, item) in enumerate(zip(users, items)):
    print(index, user, item)
0 1 4
1 2 5
2 3 6

最大和最小元素(heapq.nlargest andheapq.nsmallest)

>>> a = [random.randint(0, 100) for __ in range(100)]
>>> heapq.nsmallest(5, a)
[3, 3, 5, 6, 8]
>>> heapq.nlargest(5, a)
[100, 100, 99, 98, 98]



python列表删除操作

python列表中删除某个元素

使用del关键字删除指定位置的元素
input = [1,2,3,4]
del input[1]
使用pop方法删除指定位置的元素
input = [1,2,4,5,6]
input.pop(2)
注意list的pop方法如果指定参数的话,会删除指定索引位置的元素,如果未指定将删除list的最后一个元素。

python列表中删除某个元素所有的出现,如空字符串

while '' in classified_sentences:
classified_sentences.remove('')

python清空列表的几种方式

1. s.clear() 

2. del s[:] 

3. s[:] = [] 

4. s *= 0


python列表拷贝

python中怎么对一个列表赋值并修改不影响原来的列表?
  1. 简单列表的拷贝

    已知一个列表,求生成一个新的列表,列表元素是原列表的复制

    a=[1,2]
    b=a

    这种其实并未真正生成一个新的列表,b指向的仍然是a所指向的对象。

    后果:如果对a或b的元素进行修改,a,b的值同时发生变化:a.remove(1)则对应b也变为[2]

  2. 可以使用以下方法解决

    a=[1,2]
    b=a[:]

    这样修改a对b没有影响。修改b对a没有影响。

  3. 列表拷贝

             a = [1,2,3]

             b = a.copy()

             print(id(a), id(b))

        4.复杂列表的拷贝

              可以使用copy模块中的deepcopy函数。修改测试如下:

              import copy
              a=[1,[2]]

              b=copy.deepcopy(a)

[图解 Python 深拷贝和浅拷贝]

列表初始化值设置

music_tag = dict()
for music_name in music_names:
    music_tag.setdefault(music_name, [])
    for filename in filenames:
        if music_name in [line.strip() for line in open(join(DIR, filename))]:
            music_tag[music_name] += filename.split('.')[0]

python文件中的科学计数法的数字读入列表中并排序

for line in word_dist_file:
    word_dist_list = line.strip().split()
    word_dist_list = sorted([float(word_dist) for word_dist in word_dist_list], reverse=True)


python两个列表的操作

两个list相与操作

list1 = [1,2]
list2 = [2,3]
print(list1 and list2)

[2, 3]

python两个列表相减

方法1. 用set(集合)操作
list3 = list(set(list1) - set(list2))
set操作会将一个list转换成一个集合,重复的项会被删除。
方法2.列表解析
list3 = [i for i in list1 if i not in list2]
但是在list很大的时候,没有set方法快。

python中求两个list的交集,两个list是否有交集

list1 = [1,2]
list2 = [2,3]
print(set(list1).intersection(set(list2)))

{2}

python两个列表合并

list.extend(seq)
Note:在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

返回none

如果不想改变原来list,可以用new_list = copy.deepcopy(list)

Flattening lists扁平列表

>>> a = [[1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

>>> sum(a, [])
[1, 2, 3, 4, 5, 6]

>>> [x for l in a for x in l]
[1, 2, 3, 4, 5, 6]

>>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> [x for l1 in a for l2 in l1 for x in l2]
[1, 2, 3, 4, 5, 6, 7, 8]

>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8]

Note:1. itertools详解 

2.sum(iterable, start=None): 

Return the sum of an iterable of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the iterable is empty, return start.

3. 列表解析等要慢1.5倍

4. according to Python's documentation on sum,itertools.chain.from_iterable is the preferred method for this.

python的for循环从两个不同列表中同时取出两个元素

zip(): 如果你多个等长的序列,然后想要每次循环时从各个序列分别取出一个元素,可以利用zip()方便地实现:

ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
for (a,b,c) in zip(ta,tb,tc):
    print(a,b,c)

[python - 常用函数和全局变量--zip]


python列表其它操作

将python列表中每个元素用,分开写入文件中

(最后一个元素后面不加,,这里a中的元素必须是字符串)

a = ['12', '34', '45']
s = ','.join(a)
print(s)
12,34,45

列表解析和条件表达式

  
  
  
  
# times even numbers by 2 and odd numbers by 3
mul = [num * 3 if num % 2 else num * 2 for num in numbers]
皮皮Blog




python字典操作

python字典构建

dict(zip(names, random_numbers()))  

# output: {'James': 992, 'Andrew': 173, 'Mark': 329}

python dict字典的key必须是hashable的

key不能是list, set(否则出错TypeError: unhashable type: 'list'), 但可以是tuple


python dict字典for循环输出

dict1 = {1: 1, 2: 1, 3: 1}
for i in dict1: #等价于dic1.keys()

python 字典查找

1. 如何通过value 找出key

任何时刻dict.keys()和dict.values()的顺序都是对应的:
try:
    return dict.keys()[dict.values().index(value)]         #python3中要修改为list(dict.keys())[list(dict.values()).index(value)]
except ValueError:
    pass

Note:往dict中添加元素,keys和values加入后都是无序的!但是加入之后相对位置不变。

2. 从字典中获取元素

data = {'user': 1, 'name': 'Max', 'three': 4}

方法1:

try:

     is_admin = data['admin']

except KeyError:

     is_admin = False

方法2:

is_admin = data.get('admin', False)



使用tuple作为key,查找某个tuple(位置可互换)对应的value

print(ui_dict)
try:
    print(ui_dict[(1,3)])
except:
    try:
        print(ui_dict[(3,1)])
    except:
        print(0)
{(1, 2): '5', (3, 2): '5', (3, 1): '1', (1, 1): '1', (2, 1): '4'}
1

python字典初始化

python字典设置value初始类型,指定字典的value类型

1. collections.defaultdict([default_factory[,...]])

default_factory指定字典的value类型

from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)...
>>> d.items()

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Note:defaultdict()参数设置成int,那么就设置字典值的初始值为0了

2. dict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值

dfs = {}
...
for termid, _ in bow:
dfs[termid] = dfs.get(termid, 0) + 1
3.dict.setdefault(key, default=None) get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
上面1的代码效率高于下面的等效代码:
>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)

如果给default_dict传入int,则可以用来计数:
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
>>> d.items()

[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

指定类型的变化

d = defaultdict(int)
d[3] += 2.284684
print(d)
defaultdict(<class 'int'>, {3: 2.284684})

Using default dictionaries to represent simple trees

>>> import json
>>> tree = lambda: collections.defaultdict(tree)
>>> root = tree()
>>> root['menu']['id'] = 'file'
>>> root['menu']['value'] = 'File'
>>> root['menu']['menuitems']['new']['value'] = 'New'
>>> root['menu']['menuitems']['new']['onclick'] = 'new();'
>>> root['menu']['menuitems']['open']['value'] = 'Open'
>>> root['menu']['menuitems']['open']['onclick'] = 'open();'
>>> root['menu']['menuitems']['close']['value'] = 'Close'
>>> root['menu']['menuitems']['close']['onclick'] = 'close();'
>>> print json.dumps(root, sort_keys=True, indent=4, separators=(',', ': '))
{
    "menu": {
        "id": "file",
        "menuitems": {
            "close": {
                "onclick": "close();",
                "value": "Close"
            },
            "new": {
                "onclick": "new();",
                "value": "New"
            },
            "open": {
                "onclick": "open();",
                "value": "Open"
            }
        },
        "value": "File"
    }
}

(See https://gist.github.com/hrldcpr/2012250 for more on this.)

Mapping objects to unique counting numbers (collections.defaultdict)

>>> import itertools, collections
>>> value_to_numeric_map = collections.defaultdict(itertools.count().next)
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
>>> value_to_numeric_map['c']
2
>>> value_to_numeric_map['a']
0


python中两个字典的操作

python两个字典合并操作

dict1 = {1:1, 2:1, 3:1}
dict2 = {3:2, 4:2, 5:2}
dict1.update(dict2)
print(dict1)

Adding two dictionaries两个字典相加
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11, 'a':3, 'd':7}
z = {a: x.get(a,0)+y.get(a,0) for a in set(x) | set(y)}
print z
>>>{'a': 4, 'c': 11, 'b': 12, 'd': 7}

python字典排序

对字典按键/按值排序,用元组列表的形式返回,同时使用lambda函数来进行;

sorted(iterable[, cmp[, key[, reverse]]]
cmp和key一般使用lambda

对字典按键key排序,用元组列表的形式返回

1. 使用lambda函数

d = {3:5, 6:3, 2:4}
ds = sorted(d.items(), key=lambda item:item[0], reverse=True) #d[0]表示字典的键
print(ds)
[(6, 3), (3, 5), (2, 4)]

2.采用operator模块的itemgetter函数

from operator import itemgetter
sorted(d, key=itemgetter(1))

[python - 常用函数和全局变量:sorted内置函数]


对字典按值value排序,用元组列表的形式返回

ds = sorted(d.items(), key=lambda item:item[1], reverse=True)
print(ds)
[(3, 5), (2, 4), (6, 3)]
print(dict(ds))    #又变成无序的了
{2: 4, 3: 5, 6: 3}

分解代码:d.items() 得到[(键,值)]的列表。然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1]的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。

字典

Ordered dictionaries (collections.OrderedDict)有序字典

>>> m = dict((str(x), x) for x in range(10))
>>> print ', '.join(m.keys())
1, 0, 3, 2, 5, 4, 7, 6, 9, 8
>>> m = collections.OrderedDict((str(x), x) for x in range(10))
>>> print ', '.join(m.keys())
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>>> m = collections.OrderedDict((str(x), x) for x in range(10, 0, -1))
>>> print ', '.join(m.keys())
10, 9, 8, 7, 6, 5, 4, 3, 2, 1

[collections模块- OrderedDict]

Dictionary Comprehensions字典解析

One use for generators can be to build a dictionary, like in the first example below. This proved itself to be common enough that now there is even a newdictionary comprehension syntax for it. Both of these examples swap the keys and values of the dictionary.

      
      
      
      
teachers = {
'Andy': 'English',
'Joan': 'Maths',
'Alice': 'Computer Science',
}
# using a list comprehension
subjects = dict((subject, teacher) for teacher, subject in teachers.items())
 
# using a dictionary comprehension
subjects = {subject: teacher for teacher, subject in teachers.items()}


>>> m = {x: 'A' + str(x) for x in range(10)

}>>> m

{0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5: 'A5', 6: 'A6', 7: 'A7', 8: 'A8', 9: 'A9'}

Inverting a dictionary using a dictionary comprehension翻转字典中的key和value

>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> m
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
>>> {v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
使用zip反相字典对象

皮皮Blog



python集合操作

集合类型初始化及加入新元素(已存在就不加入)

s = {2,3,3}
print(s)
s.add(2)
print(s)

>>> A  = { 1 , 2 , 3 , 3 }
>>> A
set ([ 1 , 2 , 3 ])
>>> B  = { 3 , 4 , 5 , 6 , 7 }
>>> B
set ([ 3 , 4 , 5 , 6 , 7 ])
>>> A | B
set ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 ])
>>> A & B
set ([ 3 ])
>>> A  - B
set ([ 1 , 2 ])
>>> B  - A
set ([ 4 , 5 , 6 , 7 ])
>>> A ^ B
set ([ 1 , 2 , 4 , 5 , 6 , 7 ])
>>> (A ^ B)  = =  ((A  -  B) | (B - A))
True

[Multisets and multiset operations (collections.Counter) ]

皮皮Blog



python元组操作

命名的tuples(collections.namedtuple)

皮皮Blog



列表,元组和字符串之间的互相转换

python中有三个内建函数:str(),tuple()和list()

1. 字符串的转换

>>> s = "xxxxx"
>>> list(s)
['x', 'x', 'x', 'x', 'x']
>>> tuple(s)
('x', 'x', 'x', 'x', 'x')
>>> tuple(list(s))
('x', 'x', 'x', 'x', 'x')
>>> list(tuple(s))
['x', 'x', 'x', 'x', 'x']
列表和元组转换为字符串则必须依靠join函数
>>> "".join(tuple(s))
'xxxxx'
>>> "".join(list(s))
'xxxxx'
>>> str(tuple(s))
"('x', 'x', 'x', 'x', 'x')"



元组列表转字典

列表或元组直接转字典

1. rankDict =  dict(rank)

元组不可以直接转为字典

但可以这样:

post_data = dict(zip(["retcode", "servertime", "pcid", "nonce", "pubkey", "rsakv", "exectime"], post_ori_data))


2. dict. fromkeys(S)
S是一个列表或元组...
将S中的元素作为字典的key,value默认为None,也可以指定一个初始值,代码示例:
myDict = dict.fromkeys('hello', True)
for k in myDict.keys():
    print(k, myDict[k])
h True
e True
l True
o True

字典转元组列表

a = {1:23,8:43,3:34,9:28}
print(list(a.items()))
print(list(zip(a.keys(),a.values())))

from:http://blog.csdn.net/pipisorry/article/details/39234557

ref:30 Python Language Features and Tricks You May Not Know About

Hidden features of Python [closed]

Python: Tips, Tricks and Idioms


皮皮Blog

你可能感兴趣的:(python,list,Tuple)