python基本类型、操作及相互转换

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

Python中的“真值”

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

  • 空列表([] )

  • 空元组(() )

  • 空字典({} )

  • 空字符串('' )

  • 零值(0 )

  • 特殊对象None

  • 对象False(很明显)

Note:

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

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


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,所以如果没有指定抛出位置,则默认抛出最后一个条目。

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]

Zipping and unzipping lists and iterables

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]
清空列表的几种方式

1. s.clear()

2. del s[:]

3. s[:] = []

4. s *= 0

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: according to Python's documentation on sum,itertools.chain.from_iterable is the preferred method for this.


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. 复杂列表的拷贝

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

              import copy
              a=[1,[2]]

              b=copy.deepcopy(a)

列表初始化值设置

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循环从两个不同列表中同时取出两个元素

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)

每次循环时,从各个序列分别从左到右取出一个元素,合并成一个tuple,然后tuple的元素赋予给a,b,c

zip()函数的功能,就是从多个列表中,依次各取出一个元素。每次取出的(来自不同列表的)元素合成一个元组,合并成的元组放入zip()返回的列表中。zip()函数起到了聚合列表的功能。

将python列表中每个元素用,分开写入文件中(最后一个元素后面不加,)

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

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列表查找某个元素

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

Largest and smallest elements (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]

两个list相与操作

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

[2, 3]
python中求两个list的交集,两个list是否有交集
list1 = [1,2]
list2 = [2,3]
print(set(list1).intersection(set(list2)))

{2}



python字典操作

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()
    print(i)
1
2
3
python 字典中如何通过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加入后都是无序的!但是加入之后相对位置不变。

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.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
上面代码效率高于下面的等效代码:
>>> 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
使用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

两个字典合并操作

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排序,用元组列表的形式返回

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)]

对字典按值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
Dictionary comprehensions
>>> 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'}



Python集合操作

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

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

Multisets and multiset operations (collections.Counter)

>>> A = collections.Counter([1, 2, 2])
>>> B = collections.Counter([2, 2, 3])
>>> A
Counter({2: 2, 1: 1})
>>> B
Counter({2: 2, 3: 1})
>>> A | B
Counter({2: 2, 1: 1, 3: 1})
>>> A & B
Counter({2: 2})
>>> A + B
Counter({2: 4, 1: 1, 3: 1})
>>> A - B
Counter({1: 1})
>>> B - A
Counter({3: 1})




python元组操作

Named tuples (collections.namedtuple)元素命名的元组

>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(x=1.0, y=2.0)
>>> p
Point(x=1.0, y=2.0)
>>> p.x
1.0
>>> p.y
2.0





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

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

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

>>> 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)

即可将元组转为字典型

2. dict.fromkeys(S)

    S是一个列表或元组...

    将S中的元素作为字典的key,value默认为None,也可以指定一个初始值,代码示例:

  1. myDict = dict.fromkeys('hello'True)  
  2. for k in myDict.keys():  
  3.     print(k, myDict[k])  
  4.   
  5. True  
  6. True  
  7. True  
  8. True  
from:http://blog.csdn.net/pipisorry/article/details/39234557

ref:StarterLearningPython

30 Python Language Features and Tricks You May Not Know About

Hidden features of Python [closed]

Python: Tips, Tricks and Idioms


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章