| 知乎专栏 |
随机抽取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')]
# 定义一个二维列表 lst = [[4, 2], [1, 5], [3, 3], [2, 1]] # 使用sorted()函数和lambda表达式按照二维列表的第一列进行排序 sorted_lst = sorted(lst, key=lambda x: x[0]) print(sorted_lst)
a = ['a', 'b', 'c', 'd']
b = ['b', 'c']
# 方法1:使用列表推导式(简洁高效)
result = [x for x in a if x not in b]
print("方法1结果:", result) # 输出: ['a', 'd']
# 方法2:使用filter函数(函数式编程风格)
result = list(filter(lambda x: x not in b, a))
print("方法2结果:", result) # 输出: ['a', 'd']
# 方法3:循环遍历(原地修改原列表,不推荐但适合理解过程)
a_copy = a.copy() # 复制原列表避免遍历中修改导致的问题
for item in a_copy:
if item in b:
a.remove(item)
print("方法3结果:", a) # 输出: ['a', 'd']
>>> ','.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']
python header = ['a','b','c'] body=[1,2,3] 转成 dict. {'a':1, 'b': 2, 'c':3}
可以使用 Python 的 zip() 函数将两个列表合并为字典,zip() 会将对应索引的元素配对,然后通过 dict() 转换为字典:
将两个列表转换为字典
原理说明:
zip(header, body) 会将两个列表中对应位置的元素组合成元组,形成类似 [('a', 1), ('b', 2), ('c', 3)] 的可迭代对象。
dict() 函数会将这些元组转换为字典,元组的第一个元素作为键,第二个元素作为值。
注意事项:
如果两个列表长度不一致,zip() 会以较短的列表为准,忽略超出部分的元素。
例如:header = ['a', 'b'],body = [1, 2, 3],结果会是 {'a': 1, 'b': 2}。
header = ['a', 'b', 'c']
body = [1, 2, 3]
# 使用zip()配对后转换为字典
result_dict = dict(zip(header, body))
print(result_dict) # 输出: {'a': 1, 'b': 2, 'c': 3}
#!/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)