Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

1.7. 数据结构

1.7.1. List

随机抽取list成员

import random

# random choice from a list
for i in range(5):
    print random.choice([1, 2, 3, 5, 9])
		
		
test = []
test.append('1')
test.append('b')
test.append('c')
print(test)	
		
		

1.7.1.1. 返回索引序号

index()方法语法:

			
list.index(x[, start[, end]])

参数
x-- 查找的对象。
start-- 可选,查找的起始位置。
end-- 可选,查找的结束位置。			
			
			
			
fruits = ["apple", "banana", "cherry", "apple"]
print(fruits.index("apple")) # 输出: 0

animals = ["cat", "dog", "tiger"]
print(animals.index("dog")) # 输出: 1

numbers = [1, 2, 3, 4, 1, 1, 1, 4, 5]
print(numbers.index(4, 4, 8)) # 输出: 7
			
			

1.7.1.2. 二维列表,指定列,查找最大值

			
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

column = [row[1] for row in matrix]
max_value = max(column)

print("第二列最大值:", max_value)			
			
			

返回最大值

			
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

column = [row[1] for row in matrix]
max_value = max(column)
index = column.index(max_value)
print(index, matrix[index])			
			
			

1.7.1.3. 获得list中最大/最小值元素的索引

			
获得list中最大元素的索引

nums = [1,2,3,4,5]

nums.index(max(nums))

相应的最小值索引

nums = [1,2,3,4,5]

nums.index(min(nums))			
			
			

1.7.1.4. 用 enumerate 返回 list 索引

			
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
...
0 one
1 two
2 three			
			
			

指定开始索引下标

			
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]			
			
			

1.7.2. Set 集合

		
>>> ','.join(set);
'four,three,two,one'

>>> set('four,three,two,one'.split(','));
{'one', 'four', 'three', 'two'}

>>> fruit = [ 'banana', 'orange', 'pineapple' ]
>>> set(fruit)
{'banana', 'pineapple', 'orange'}		
		
		

1.7.2.1. 创建集合

			
>>> set = {'a','b','c'}
>>> set
set(['a', 'c', 'b'])

>>> set = {"one", "two", "three","one"}
>>> set
set(['three', 'two', 'one'])		
			
			
			
set1 = {1, 2, 3, 4}
print(set1)

set2 = set([4, 5, 6, 7])
print(set2)			
			
			

1.7.2.2. 添加元素

添加元素到集合有两个方法,分别是 add() 和 update()

			
>>> set.add('four')
>>> set
set(['four', 'three', 'two', 'one'])
			
			
			
company = set(("Google", "OpenAI", "Facebook"))
company.update({"Microsoft"})
company.update({"Aliyun","Taobao"})
print(company)

company.update([1,2],[5,6])
print(company)			
			
			
			
{'Facebook', 'Google', 'Microsoft', 'Taobao', 'Aliyun', 'OpenAI'}
{'Facebook', 1, 2, 5, 6, 'Aliyun', 'Google', 'OpenAI', 'Microsoft', 'Taobao'}			
			
			

1.7.2.3. 删除元素

			
company = set({'Facebook', 'Google', 'Microsoft', 'Taobao', 'Aliyun', 'OpenAI'})
print(company)
company.remove("OpenAI")
print(company)
company.discard("Aliyun")
print(company)
			
			

随机移除一个元素

			
company.pop()
print(company)			
			
			

			
{'Taobao', 'Facebook', 'Aliyun', 'Microsoft', 'OpenAI', 'Google'}
{'Taobao', 'Facebook', 'Aliyun', 'Microsoft', 'Google'}
{'Taobao', 'Facebook', 'Microsoft', 'Google'}
{'Facebook', 'Microsoft', 'Google'}			
			
			

1.7.2.4. 清空集合

			
>>> company = set(("Google", "Microsoft", "OpenAI"))
>>> company.clear()
>>> print(company)
set()			
			
			

1.7.2.5. 合并集合

			
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
 
z = x.union(y) 
 
print(z)			
			
			

			
x = {"a", "b", "c"}
y = {"d", "e", "f"}
z = {"g", "i", "j"}
 
result = x.union(y, z) 
 
print(result)			
			
			

1.7.3. Dict 字典

1.7.3.1. 随机选择字典的 key 和 value

随机字典的 key 和 value

			
			<![CDATA[
names = {1: '张三', 2: '李四', 3: '王五', 4: '赵六', 5: '牛七', 6: '马八'}
print(random.choice(list(names.keys())))
print(random.choice(list(names.values())))			
			
			

1.7.3.2. 字典合并

			
dict1 = {'name','neo'}
dict2 = {'nickname','netkiller'}
dict1.update(dict2)
print(dict1)			
			
			

			
{'name', 'neo', 'nickname', 'netkiller'}			
			
			

1.7.3.3. 取 Value 最大值

			
data = {
    "Neo": 5,
    "Netkiller": 10,
    "BG7NYT": 8,
}

ret = max(data, key=lambda x: data[x])
print(ret)
			
			

1.7.3.4. 指定 key 取 value 最大值

			
data = [
    {
      "question": "为什么过只加汇摇晃",
      "answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
      "ratio": 0,
      "distance": 41.112388610839844
    },
    {
      "question": "吊厢过之家为什么会摇晃",
      "answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
      "ratio": 0,
      "distance": 42.78510284423828
    },
    {
      "question": "嗦道为啥会摇晃",
      "answer": "因为支架是由很多支索小圆轮组成的,所以吊厢过索轮时会有轻微的震动和摇晃,这些都是正常的",
      "ratio": 1,
      "distance": 44.00849914550781
    }
   
  ]

ret = max(data, key=lambda dic: dic['ratio']) 
print(ret)
			
			

1.7.3.5. 字典求和

			
count = sum(dict.values())			
			
			

1.7.3.6. 对 value 排序后返回 key

			
data = {
    "Neo": 5,
    "Netkiller": 10,
    "BG7NYT": 8,
}

ret = sorted(data, key=lambda x: data[x])
print(ret)


ret = sorted(data, key=lambda x: data[x],reverse=True)
print(ret)

ret = sorted(data, key=lambda x: data[x],reverse=False)
print(ret)			
			
			

返回结果

			
['Neo', 'BG7NYT', 'Netkiller']
['Netkiller', 'BG7NYT', 'Neo']
['Neo', 'BG7NYT', 'Netkiller']			
			
			

1.7.4. Iterator

		
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 创建 Iterator 对象
it = iter([1, 2, 3, 4, 5])
# 开始循环
while True:
    try:
        # 获得下一个值
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration终止循环
        break		
		
		

设置结束标志符

		
#!/usr/bin/python
# -*- coding: UTF-8 -*-

it = iter([1, 2, 5, 4, 3])
while True:
    x = next(it, 'a')
    print(x)
    if x == 'a':
        break		
		
		

1.7.5. 序列化

		 
import shelve

with shelve.open("/var/tmp/test") as db:
	db["hello"] = "helloworld"

with shelve.open("/var/tmp/test") as db:
	for k, v in db.items():
		print(k, ":", v)		
		
		
		 
import shelve, json

data = json.loads(json.dumps({"800": "AAAA", "900": "BBBB", "1000": "CCCC"}))
print(data, type(data))
with shelve.open("/var/tmp/test", "n") as db:
	for k, v in data.items():
		db[k] = v

with shelve.open("/var/tmp/test") as db:
	for k, v in db.items():
		print(k, ":", v)
		
		

1.7.6. 队列

		 
import queue

q = queue.SimpleQueue()

for n in range(10):
	q.put(n)

print("队列数量:", q.qsize())

while not q.empty():
	print(q.get())

print("队列状态:", q.empty())
			
		

先进先出队列,保持队列最大尺寸,超过尺寸自动出队

		 
from queue import Queue

q = Queue(maxsize=3)

for i in range(10):
	if q.full():
		q.get()
	q.put(i, block=False)


print(type(q.queue), q.queue)

while not q.empty():
	i = q.get(block=False)
	print(i)		
		
		
		 
from queue import Queue

q = Queue(maxsize=10)

for i in range(20):
	if q.full():
		q.get()
	q.put(i, block=False)


print(type(q.queue), q.queue)

for n in range(5):
	if not q.empty():
		i = q.get(block=False)
		print(i)