西维蜀黍

【Python】I/O - 输入

input()

>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<type 'int'>               # 整型
>>> a = input("input:")    
input:"runoob"           # 正确,字符串表达式
>>> type(a)
<type 'str'>             # 字符串
>>> a = input("input:")
input:runoob               # 报错,不是表达式
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>

raw_input() - 将所有输入作为字符串看待

>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串
>>>
  ...


【Python】Python 一切皆对象

Python的一等公民

Python 中的一等公民,都具有以下特性:

  • 可以赋值给一个变量
  • 可以添加到集合对象中
  • 可以作为参数传递给函数
  • 可以当做函数的返回值

针对赋值给变量及添加到集合对象中,代码予以展示:

def func():
    print 'the func function is executed'


class Test:
    def __init__(self):
        print 'An instance of Test class is initialized'

obj_list = []
obj_list.append(func)
obj_list.append(Test)

for item in obj_list:							# 添加至集合对象中
    print(item())
  ...


【Python】Basics - Built-in Function(内置函数)

range() - 生成 list

Using only one argument in range()

print("Print first 5 numbers using range function")
for i in range(5):
    print(i, end=', ')

Output:

Print first 5 numbers using range function
0, 1, 2, 3, 4,

要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  ...


【Python】String

String 格式化

在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'

你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符有:

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
  ...


【Python】Collection - dict

dict

一个非常有用的 Python 內置数据类型是 字典 (参见 映射类型 — dict)。字典在其他语言里可能会被叫做 联合内存 或 联合数组。与以连续整数为索引的序列不同,字典是以 关键字 为索引的,关键字可以是任意不可变类型,通常是字符串或数字。如果一个元组只包含字符串、数字或元组,那么这个元组也可以用作关键字。但如果元组直接或间接地包含了可变对象,那么它就不能用作关键字。列表不能用作关键字,因为列表可以通过索引、切片或 append() 和 extend() 之类的方法来改变。

理解字典的最好方式,就是将它看做是一个 键: 值 对的集合,键必须是唯一的(在一个字典中)。一对花括号可以创建一个空字典:{} 。另一种初始化字典的方式是在一对花括号里放置一些以逗号分隔的键值对,而这也是字典输出的方式。

字典主要的操作是使用关键字存储和解析值。也可以用 del 来删除一个键值对。如果你使用了一个已经存在的关键字来存储值,那么之前与这个关键字关联的值就会被遗忘。用一个不存在的键来取值则会报错。

对一个字典执行 list(d) 将返回包含该字典中所有键的列表,按插入次序排列 (如需其他排序,则要使用 sorted(d))。要检查字典中是否存在一个特定键,可使用 in 关键字。

以下是使用字典的一些简单示例

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
  ...


【Python】Collection - list

List

In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.

The “empty list” is just an empty pair of brackets [ ]. The ‘+’ works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

Here’s a simple example of a list that contains a few kinds of bicycles:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles)

list 的常用方法

  • list.remove(x) - 移除列表中第一个值为 x 的元素。如果没有这样的元素,则抛出 ValueError 异常。

  • list.pop([i]) - 删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。( 方法签名中 i 两边的方括号表示这个参数是可选的,而不是要你输入方括号。你会在 Python 参考库中经常看到这种表示方法)。

  • list.clear() - 删除列表中所有的元素。相当于 del a[:] 。

  • list.index(x[, start[, end]]) - 返回列表中第一个值为 x 的元素的从零开始的索引。如果没有这样的元素将会抛出 ValueError 异常。可选参数 start 和 end 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。

  • list.count(x) - 返回元素 x 在列表中出现的次数。

  • list.sort(key=None, reverse=False) - 对列表中的元素进行排序(参数可用于自定义排序,解释请参见 sorted())。

  • list.reverse() - 反转列表中的元素。

  • list.copy() - 返回列表的一个浅拷贝。相当于 a[:] 。

  ...


【Python】Python Style Guide

Python Style Guide

  ...


【JavaEE】Java Servlet和 JSP(JavaServer Pages)

狭义的Servlet是指Java语言中的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。

  ...


【Database】索引 - 聚集索引(Clustered Index)与非聚集索引(Non-clustered Index)

聚集索引(Clustered Index)与非聚集索引(Non-clustered Index)

聚集索引(Clustered Index) - storing all row data within the index)

Clustering alters the data block into a certain distinct order to match the index, resulting in the row data being stored in order. Therefore, only one clustered index can be created on a given database table. Clustered indices can greatly increase overall speed of retrieval, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items is selected.

Since the physical records are in this sort order on disk, the next row item in the sequence is immediately before or after the last one, and so fewer data block reads are required. The primary feature of a clustered index is therefore the ordering of the physical data rows in accordance with the index blocks that point to them. Some databases separate the data and index blocks into separate files, others put two completely different data blocks within the same physical file(s).

非聚集索引(Non-clustered Index)- storing only references to the data within the index

The data is present in arbitrary order, but the logical ordering is specified by the index. The data rows may be spread throughout the table regardless of the value of the indexed column or expression. The non-clustered index tree contains the index keys in sorted order, with the leaf level of the index containing the pointer to the record (page and the row number in the data page in page-organized engines; row offset in file-organized engines).

In a non-clustered index,

  • The physical order of the rows is not the same as the index order.
  • The indexed columns are typically non-primary key columns used in JOIN, WHERE, and ORDER BY clauses.

There can be more than one non-clustered index on a database table.

索引数据的存储方式 - 聚集索引(聚簇索引,Clustered Index)

聚集索引(clustered index),也称为聚簇索引。

聚簇索引并不是一种单独的索引类型,而是一种索引数据的存储方式。

当表有聚簇索引时,它的行数据实际上存储在索引的叶子页(leaf page)中。因为无法同时把数据行存放在两个不同的地方,所以一张表只能有一个聚簇索引。

  ...


【Django】通过 ORM 访问 MySQL,插入 Emoji 报错

Problem

>>> paras = {u'name': u'\U0001f600'}
>>> from core import models
>>> models.Channel.objects.create(**paras)
Traceback (most recent call last):
    ...
  File "/Library/Python/2.7/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
InternalError: (1366, u"Incorrect string value: '\\xF0\\x9F\\x98\\x80' for column 'name' at row 1")

通过 ORM插入一条数据,在其中的一个类型为varchar的字段中插入一个 Emoji 表情,我插的是😀(对应的字符串为u'\U0001f600'),插入后:提示以下错误:

{InternalError}(1366, u"Incorrect string value: '\\xF0\\x9F\\x98\\x80' for column 'name' at row 1")
  ...