知乎专栏 |
随机抽取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)
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
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])
获得list中最大元素的索引 nums = [1,2,3,4,5] nums.index(max(nums)) 相应的最小值索引 nums = [1,2,3,4,5] nums.index(min(nums))
>>> 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')]
>>> ','.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'}
>>> 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)
添加元素到集合有两个方法,分别是 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'}
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'}
>>> company = set(("Google", "Microsoft", "OpenAI")) >>> company.clear() >>> print(company) set()
随机字典的 key 和 value
<![CDATA[ names = {1: '张三', 2: '李四', 3: '王五', 4: '赵六', 5: '牛七', 6: '马八'} print(random.choice(list(names.keys()))) print(random.choice(list(names.values())))
dict1 = {'name','neo'} dict2 = {'nickname','netkiller'} dict1.update(dict2) print(dict1)
{'name', 'neo', 'nickname', 'netkiller'}
data = { "Neo": 5, "Netkiller": 10, "BG7NYT": 8, } ret = max(data, key=lambda x: data[x]) print(ret)
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)
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']
#!/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
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)
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)