1. list列表扩展的方式有几种(或者说添加元素的方法)
方法一:append
Append object to the end of the list.————将对象追加到列表的末尾。
语法:append(self, object, /)
方法二:extend
Extend list by appending elements from the iterable.——通过从可迭代对象追加元素来扩展列表。
语法:extend(self, iterable, /)
方法三:insert
Insert object before index. ————在索引之前插入对象。
语法:insert(self, index, object, /)
2. 对["cherry", "litchi", "strawberry", "mangosteen", "pomelo", "pineapple", "pitaya", "durian"]进行默认排序
对上面的列表使用第三个字母进行排序
使用sort命令
Sort the list in ascending order and return None. ——按升序对列表进行排序,并返回 None。
语法:sort(self, /, *, key=None, reverse=False)
默认排序:
按首字母顺序排序,如果首字母相同则按照第二个字母顺序排序,以此类推
第三个字母进行排序:
先去定义一个函数,此函数仅提取个元素的第三个字母
def good_function(x):
return (x[3])
再将sort命令中的key赋值为函数good_function
3.dict中所有方法的使用(先写源代码再写样例)
help(dict)
使用python内置的帮助,获得dict的使用方法
1、clear
| clear(...) | D.clear() -> None. Remove all items from D. clear() -> None. 删除所有项目
2、copy
| copy(...)
| D.copy() -> a shallow copy of D
D.copy() -> D 的浅层副本
3、get
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
如果 key 在字典中,则返回 key 的值,否则返回默认值。
4、items
| items(...)
| D.items() -> a set-like object providing a view on D's items
D.items() ->一个类似集合的对象,提供 D 项的视图
5、keys
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
D.keys() ->一个类似集合的对象,提供 D 键的视图
6、pop
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
D.pop(k[,d]) -> v,删除指定的键并返回相应的值。
| If key is not found, default is returned if given, otherwise KeyError is raised
如果未找到 key,则返回 default(如果给定),否则引发 KeyError
7、popitem
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
删除(键、值)对并将其作为 2 元组返回。
| Pairs are returned in LIFO (last-in, first-out) order.
成对按后进先出(后进先出)顺序返回。
| Raises KeyError if the dict is empty.
如果字典为空,则引发 KeyError。
8、setdefault
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
| 如果键不在字典中,则插入值为默认值的键。
| Return the value for key if key is in the dictionary, else default.
如果 key 在字典中,则返回 key 的值,否则返回默认值。
9、 update
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
D.update([E, ]**F) -> None. 从字典/可迭代 E 和 F 更新 D。
| 如果 E 存在并且具有 .keys() 方法,则对于 E 中的 k:D[k] = E[k]
| 如果 E 存在并且缺少 .keys() 方法,则对于 E 中的 k, v:D[k] = v
| 在任何一种情况下,这后面跟着:对于F中的k:D[k] = F[k]
10、values
| values(...)
| D.values() -> an object providing a view on D's values
| values() ->一个对象,提供 D 值的视图
11、fromkeys
| fromkeys(iterable, value=None, /) from builtins.type
| Create a new dictionary with keys from iterable and values set to value.
创建一个新字典,其中包含可迭代的键并将值设置为值。