Python容器

列表[]

列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能。

创建

直接创建

list1 = ['a','b']
list2 = [1,2]

list函数创建

list3 = list("hello")
print list3

输出

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

lista = [0] * 6

过滤

 [elem for elem in li if len(elem) > 1]
 
 # 用filter过滤
 list(filter(lambda x: x[1]<0, exp.local_exp[1]))

划分

a=[1,2,3,4]
#不包括1
a[:1]
#输出[1]
#包括2
a[2:]
#输出[3、4]

判断数组为空

if not nums:
    return None

遍历索引和元素

#遍历列表, 打印索引和元素
names = ['Tom', 'Jerry', 'Marry']
for index, name in enumerate(names):
    print('names[{}] = {}'.format(index, name))
 
 
打印结果:
names[0] = Tom
names[1] = Jerry
names[2] = Marry

把列表中某个值划分出去

if featureVec[axis] == value:
    reducedFeatVec = featureVec[:axis]
    reducedFeatVec.extend(featureVec[axis+1:])

二维列表

dataSet = [[1, 1, 'yes'],
               [1, 1, 'yes'],
               [1, 0, 'no'],
               [0, 1, 'no'],
               [0, 1, 'no']]

定义一个5×4的都是0的二维数组

c=[[0 for i in range(4)] for j in range(5)]

合并

circle_file = glob.glob(os.path.join(self.resource_dir, 'circle/*.png'))
table_file  = glob.glob(os.path.join(self.resource_dir, 'table/*.png'))
 # 直接相加
 self.jump_file = [cv2.imread(name, 0) for name in circle_file + table_file] 

generator转list

import jieba
# jieba的cut返回的是一个generator
a = jieba.cut('我喜欢吃土豆')
b = list(a)

列表扩展的两种方式

a=[1,2,3]
b=[4,5,6]
a.append(b)

[1,2,3,[4,5,6]]


a.extend(b)
[1,2,3,4,5,6]

保存为csv

元组()

元组与列表一样,也是一种序列,唯一不同的是元组不能被修改(字符串其实也有这种特点)。

创建

t1=1,2,3
t2="jeffreyzhao","cnblogs"
t3=(1,2,3,4)
t4=()
t5=(1,)
print t1,t2,t3,t4,t5

输出:

(1, 2, 3) (‘jeffreyzhao’, ‘cnblogs’) (1, 2, 3, 4) () (1,)

从上面我们可以分析得出:

a、用逗号分隔一些值,元组自动创建完成

b、元组大部分时候是通过圆括号括起来的;

c、空元组可以用没有包含内容的圆括号来表示;

d、只含一个值的元组,必须加个逗号(,);

list转元组

tuple函数和序列的list函数几乎一样:以一个序列作为参数并把它转换为元组。如果参数就是元组,那么该参数就会原样返回

t1=tuple([1,2,3])
t2=tuple("jeff")
t3=tuple((1,2,3))
print t1
print t2
print t3
t4=tuple(123)
print t4

输出:

(1, 2, 3)
(‘j’, ‘e’, ‘f’, ‘f’)
(1, 2, 3)

t4=tuple(123)
TypeError: ‘int’ object is not iterable

词典{}

prices = {
    'A':123,
    'B':450.1,
    'C':12,
    'E':444,
}

prices['A']

创建词典

>>>dict()                        # 创建空字典
{}
>>> dict(a='a', b='b', t='t')     # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1} 
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>>

读取文件创建词典

#读取代码
fr = open('dic.txt','r')
dic = {}
keys = [] #用来存储读取的顺序
for line in fr:
    v = line.strip().split(':')
    dic[v[0]] = v[1]
    keys.append(v[0])
fr.close()
print(dic)
#写入文件代码 通过keys的顺序写入
fw = open('wdic.txt','w')
for k in keys:
    fw.write(k+':'+dic[k]+'\n')
 
fw.close()

转list

li = dict.items()

结果类似于

[(u'11', 50808340), (u'1101', 9842378)]

排序

转为list后再排序


判断key是否存在

#生成一个字典
d = {'name':{},'age':{},'sex':{}}
#打印返回值
print d.has_key('name')
#结果返回True

判断词典是否包含某个元素

labelCount={}
for feature in dataSet:
    label = feature[-1]
    if label not in labelCount[label]: labelCount[label] = 0 

词典的遍历

iteritems

sentences = ["我喜欢吃土豆","土豆是个百搭的东西","我不喜欢今天雾霾的北京"]

words = []
for doc in sentences:
    words.append(list(jieba.cut(doc)))

dic = corpora.Dictionary(words)

for word,index in dic.token2id.iteritems():
    print word + ', index: ' + str(index)

在3.x 里 用 items()替换iteritems()

增加元素

#比如有个词典
action = {
  "_index": elastic_urls_index,
  "_type": doc_type_name,
  "_id": data[0],
  "_source": {
  "iclick_id": data[0],
  "onsite_id": data[1],
  "create_time": self.today_2
  }
}

#要增加元素
data['_soupyrce']['age'] = 'aa'

提取文本的高频词

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time"]


stoplist = set('for in and'.split())
texts = [ [word for word in document.lower().split() if word not in stoplist ] for document in documents]

from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
    for word in text:
        frequency[word]+=1

texts = [ [word for word in text if frequency[word]>1] for text in texts  ]

映射mapping

集合set

定义

aaa = set()

增加

aaa.add(1)

判断是否在集合

if 1 in aaa:

数组转集合

a = [11,22,33,44,11,22]  
b = set(a)

通过set去除停用词

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time"]


stoplist = set('for in and'.split())
texts = [ [word for word in document.lower().split() if word not in stoplist ] for document in documents]

set增加数据

vocabSet = set([])
for document in dataSet:
        vocabSet = vocabSet | set(document) 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容