字符串
#Python字符串是不可变对象,一本对字符串操作的API返回的都是一个新的字符串
prince_str = '30.14,29.58,26.36,32.56,32.82'
print '旧的price_str_id = {}'.format(id(prince_str))
prince_str = prince_str.replace(',', ' ')
print '新的price_str_id = {}'.format(id(prince_str))
print prince_str
输出结果为
旧的price_str_id = 42941648
新的price_str_id = 38571832
列表
#列表是一个有序容器,可以对元素进行增、删、改操作
price_array = prince_str.split(' ')
print price_array
price_array.append('32.82')
print price_array
#remove只移除第一次出现的数据
price_array.remove('32.82')
print price_array
输出结果为
['30.14', '29.58', '26.36', '32.56', '32.82']
['30.14', '29.58', '26.36', '32.56', '32.82', '32.82']
['30.14', '29.58', '26.36', '32.56']
集合
#集合是一个无续的容器,且集合中的元素无重复
price_array.append('32.82')
print price_array
print set(price_array)
输出结果为
['30.14', '29.58', '26.36', '32.56', '32.82', '32.82']
set(['26.36', '29.58', '30.14', '32.56', '32.82'])
列表推导式
data_base = 20180118
#ind为索引,_为当前值
date_array = [str(data_base + ind) for ind, _ in enumerate(price_array)]
print date_array
输出结果为
['20180118', '20180119', '20180120', '20180121', '20180122', '20180123']
zip
#zip可同时迭代多个序列,每次分别从一个序列中取一个元素,一旦其中某个序列到达结果,则迭代结束
stock_tuple_list = [(date, price) for date, price in zip(date_array, price_array)]
print '20180118日价格:{}'.format(stock_tuple_list[0][1])
print stock_tuple_list
输出结果为
20180118日价格:30.14
[('20180118', '30.14'), ('20180119', '29.58'), ('20180120', '26.36'), ('20180121', '32.56'), ('20180122', '32.82'), ('20180123', '32.82')]
可命名元组:namedtuple
from collections import namedtuple
stock_namedtuple = namedtuple('stock', ('date', 'price'))
stock_namedtuple_list = [stock_namedtuple(date, price) for date, price in zip(date_array, price_array)]
print '20180118日价格:{}'.format(stock_namedtuple_list[0].price)
print stock_namedtuple_list
输出结果为
20180118日价格:30.14
[stock(date='20180118', price='30.14'), stock(date='20180119', price='29.58'), stock(date='20180120', price='26.36'), stock(date='20180121', price='32.56'), stock(date='20180122', price='32.82'), stock(date='20180123', price='32.82')]
字典推导式
'''
stock_dict = {date: price for date, price in zip(date_array, price_array)}
print '20180118日价格:{}'.format(stock_dict['20180118'])
print stock_list
'''
输出结果为
20180118日价格:30.14
{'20180122': '32.82', '20180123': '32.82', '20180120': '26.36', '20180121': '32.56', '20180119': '29.58', '20180118': '30.14'}
有序字典:OrderedDict
from collections import OrderedDict
stock_dict = OrderedDict((date, price) for date, price in zip(date_array, price_array))
根据key值升序排列
print stock_dict
print stock_dict.keys()
print(min(zip(stock_dict.values(), stock_dict.keys())))
输出结果为
OrderedDict([('20180118', '30.14'), ('20180119', '29.58'), ('20180120', '26.36'), ('20180121', '32.56'), ('20180122', '32.82'), ('20180123', '32.82')])
['20180118', '20180119', '20180120', '20180121', '20180122', '20180123']
('26.36', '20180120')
网友评论