markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
要实现类似上一小节的“返回值”效果,仍然可以使用加号或者星号两种方式: | x = [1, 4, 3, 2]
print(sorted(x, reverse=True)) | [4, 3, 2, 1]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
反序列表反序有三种方式:- 就地反序: `x.reverse()`- 带返回值的反序: - 利用 `reversed` 生成器: `list(reversed(x))` - 利用步长为 -1 的切片: `x[::-1]` | x = [1, 4, 3, 2]
x_copy = [1, 4, 3, 2]
x.reverse()
y1 = list(reversed(x_copy))
y2 = x_copy[::-1]
print(x, x==y1, x==y2) | [2, 3, 4, 1] True True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
查询要查询一个元素是否在列表中,使用 `in` 关键字: | x = [1, 2, 3, 4]
print(2 in x, 5 in x) | True False
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
相反地,要确定一个元素是否不再列表中,使用 `not in` 来取非: | x = [1, 2, 3, 4]
print(2 not in x, 5 not in x) | False True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
要查询一个元素在列表中的位置,使用 `x.index(item)` 。* 如果列表中该元素出现了多次, `x.index()` 只会返回最靠前的那项对应的索引序数。* 如果要返回该元素在列表中出现的所有位置,可以使用列表解析(参考下方的[列表解析](列表解析)一节)功能。 | x = [1, 2, 3, 2]
item = 2
y1 = x.index(item)
y2 = [i for i, v in enumerate(x) if v == item]
print(y1, y2, sep='\n') | 1
[1, 3]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
如果 `item` 不在列表中,这样会弹出 ValueError 错误,提示你要查询的对象并不在列表中: | x.index(5) | _____no_output_____ | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
使用 `x.count()` 函数,可以避免该错误: | x = [1, 2, 3, 2]
print(x.count(2), x.count(5)) | 2 0
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
删除 按索引删除用 `x.pop()` 弹出列表末尾的元素,或用 `x.pop(index)` 弹出第 index 位的元素: | x = [1, 2, 3, 4]
y = x.pop()
print(y, x)
x = [1, 2, 3, 4]
y = x.pop(2)
print(y, x) | 3 [1, 2, 4]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
或者直接用 `del(index)` 命令来删除元素 `x[index]` : | x = [1, 2, 3, 4]
del(x[1])
print(x) | [1, 3, 4]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
按值删除 给定一个值 `item` ,用 `x.remove(item)` 可以删除列表中等于 `item` 的项:* 类似于 `x.index()` ,它只会删除最靠前的匹配项。* 考虑使用列表解析(参考下方的[列表解析](列表解析)一节)来移除所有的匹配项。 | x = [1, 2, 3, 2]
x_copy = [1, 2, 3, 2]
item = 2
x.remove(item)
y = [k for k in x_copy if k != item]
print(x, y, sep='\n') | [1, 3, 2]
[1, 3]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
清空列表使用 `x.clear()` 来清空列表为 `[]` : | x = [1, 2, 3, 4]
x.clear()
print(x) | []
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
最值用 `max()` 或 `min()` 函数返回列表中的最值。类似于 `len()` ,这两个函数对其他的序列变量类型也同样有效。 | x = [1, 3, 4, 2]
print(min(x), max(x)) | 1 4
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
高级列表操作 列表展开可以“就地”把列表拆开成多个以逗号分隔的元素。除了上文提到的展开为列表中的项(比如 `[1, *x, 2]` ),更常见的是拆成函数的传入参数。比如取余函数 `divmod()` 接受两个参数: | x = [7, 2]
print(divmod(*x)) # 7÷2=3 … 1 | (3, 1)
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
.. _list-comprehension: 列表解析列表解析(也称列表推导)通过 for 循环与 if 判断来筛选列表中的元素。 | x = [1, 2, 3, 4, 5, 6]
y = [k+10 for k in x[:3]]
z = [k for k in x if k % 2 == 1]
print(y, z, sep='\n') | [11, 12, 13]
[1, 3, 5]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
元组Python 中的元组与列表类似,但是元素不可变。- 元组与列表有不同的使用场景。- 元组的元素之间以逗号隔开,外侧的圆括号是可选的。 | x = 1, 2, 3 # 等同于 x = (1, 2, 3)
y = () # 空元组
z = (1,) # 单元素元组 | _____no_output_____ | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
元组也可以解包,将内部值赋给多个变量: | a, b, c = x
print(a, b, c) | 1 2 3
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
元组的索引与列表的方式一致,只是不能赋值给元组中的元素: | x = 1, 2, 3, 4, 5
x[::2] | _____no_output_____ | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
元组的长度也可以用 `len()` 函数获取: | x = 1, 2, 3
print(len(x)) | 3
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字符串字符串是一种不可变序列。因此,字符串不存在“就地改动”,任何字符串方法都不会改变原字符串的值。它在创建时可以用单引号包括,也可以用双引号包括。内部的引号可以用反斜线 `\` 转义: | x = "It's a string."
y = 'It\'s a string.'
print(x, y, x == y) | It's a string. It's a string. True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字符串可以用加号与乘号来进行连接与重复;如果要连接的均是字符串面值(直接用引号括起的值,而不是字符串变量),可以用空格进行连接。 | x = "abc" * 3 + "def"
y = ("This is a single-line string "
"but I can write it across lines.")
z = x + 'qwe' # 字符串变量也可用加号与面值连接
print(x, y, z, sep='\n') | abcabcabcdef
This is a single-line string but I can write it across lines.
abcabcabcdefqwe
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
多行字符串可以用三个连续的单引号(或双引号)包括。多行字符串内容的所有换行都会被保留;可以在行尾添加一个反斜线 `\` 来忽略当前行的换行: | x = """\
This is
a multiline
string.
"""
print(x) | This is
a multiline
string.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
强制类型转换用 `str()` 可以强制将其他类型转换为字符串(如果能够转换): | x = 123
y = True
z = [3, [1, 2], 4]
print(str(x), str(y), str(z), sep='\n') | 123
True
[3, [1, 2], 4]
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字符串也可以转换为列表,本质是按字符依次拆开: | x = "abcdefg"
print(list(x)) | ['a', 'b', 'c', 'd', 'e', 'f', 'g']
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
转义与 r 字符串常见的转移字符包括:| 字符 | 含义 || --- | :--- || `\b` | 退格 || `\n` | 换行 || `\r` | 回车(移动到行首) || `\t` | 制表符 || `\\` | 被转义的反斜线 |如果不想让反斜线进行转义,在字符串的 **左侧引号之前** 添加 `r` 实现: | x = "String with\tTAB."
y = r"String with\tTAB."
print(x, y, sep='\n') | String with TAB.
String with\tTAB.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字符串索引字符串的索引仍然是字符串。Python 中没有字符类型,单个字符只是长度为 1 的字符串。字符串的索引仍然支持 | x = "This is a string."
x[:6]
x[::2] | _____no_output_____ | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
唯一不同于列表索引的是,字符串在切片选取时,可以超出索引范围而不报错: | x = "This is a string."
print(x[5:2333]) | is a string.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
分割字符串Python 中字符串分割函数主要有 `split()` , `rsplit()` 与 `splitline()` 三个方法。 使用 `x.split(sep, maxsplit)` 来用 sep 字符串分割字符串 `x` ,并指定最多分割 maxsplit 次:- 分割字符串长度可以大于 1- 默认的 `maxsplit=-1` ,即会完全分割字符串 | x = "This is a string."
print(x.split('s')) # 默认完全分割
print(x.split('s', 1)) # 最多分割 1 次,即分割成 2 份
print(x.split('z')) # 空分割
print(x.split()) # 默认以空格分割 | ['Thi', ' i', ' a ', 'tring.']
['Thi', ' is a string.']
['This is a string.']
['This', 'is', 'a', 'string.']
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
我们经常把这个技巧用在 for 循环语句中: | fruits = "apple,pear,orange,banana"
for fruit in fruits.split(','):
print(fruit) | apple
pear
orange
banana
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
Python 还提供了 `rsplit()` ,可以从字符串的右侧开始分割。从下例比较两者的区别: | x = "This is a string."
print(x.split('s', 1))
print(x.rsplit('s', 1)) | ['Thi', ' is a string.']
['This is a ', 'tring.']
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
最后是 `splitlines(keepends=False)` ,它可以按行分隔符集中的所有符号进行分割(因此比手动地使用 `split('\n')` 的效果更好):- 在 `keepends=True` 时,它能保留换行符。- 关于该函数认定的换行符号集,参考 [官方文档:str.splitlines()](https://docs.python.org/zh-cn/3/library/stdtypes.html?highlight=joinstr.splitlines) 。- 它与 `split()` 函数的另一个差别是对末尾空白行的处理,读者可以参考下例。 | x = "line 1\nline 2\r\nline 3\n"
print(x.splitlines())
print(x.splitlines(keepends=True))
print(x.split('\n')) # 多一行 | ['line 1', 'line 2', 'line 3']
['line 1\n', 'line 2\r\n', 'line 3\n']
['line 1', 'line 2\r', 'line 3', '']
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
合并字符串:join()与 `x.split(sep)` 相反, 函数 `sep.join(lst)` 则是将一个列表用指定的分割符连接起来,组成一个字符串: | data = ["apple", "pear", "orange", "banana"]
s = ' ~ '.join(data)
print(s) | apple ~ pear ~ orange ~ banana
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
替换子字符串:replace()字符串替换方法 `x.split(old, new, count)` 用 new 来替换(从左向右)前 count 次搜索到的 old 子字符串。 | x = "This is a string."
y1 = x.replace("s", "t")
y2 = x.replace("s", "t", 2)
print(y1, y2, sep='\n') | Thit it a ttring.
Thit it a string.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
检查首尾匹配:startswith() / endswith()用 `x.startswith(prefix)` 与 `x.endswith(suffix)` 这两个方法来检查字符串首尾端的子字符串是否匹配 prefix 或 suffix。比较常用的情形可能是检查文件的扩展名: | files = ["doc-A.txt", "doc-B.md", "Doc-C.txt"]
for f in files:
if f.startswith('doc'):
print(f"doc - {f}")
if f.endswith('txt'):
print(f"txt - {f}") | doc - doc-A.txt
txt - doc-A.txt
doc - doc-B.md
txt - Doc-C.txt
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
清除首尾字符:strip()用 `strip()` 清除两侧匹配的字符串,或者用 `lstrip()` 单独清除左侧的,或用 `rstrip()` 单独清除右侧的。 | files = ["doc-A.txt", "doc-B.md", "Doc-C.txt"]
for f in files:
s = (f"strip: {f.strip('d'):10}\t"
f"lstrip: {f.lstrip('doc-'):10}\t"
f"rstrip: {f.rstrip('txt')}")
print(s) | strip: oc-A.txt lstrip: A.txt rstrip: doc-A.
strip: oc-B.m lstrip: B.md rstrip: doc-B.md
strip: Doc-C.txt lstrip: Doc-C.txt rstrip: Doc-C.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
默认的 `strip()` 函数会清除字符串两侧的空格——这有时在读取文件时会用到: | x = "line 1 \n line 2 \r\n\tline 3\n"
lines = x.splitlines()
lines_strip = [line.strip() for line in lines]
print(lines, lines_strip, sep='\n') | ['line 1 ', ' line 2 ', '\tline 3']
['line 1', 'line 2', 'line 3']
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字符串格式化:format() 与 f 字符串 字符串格式化是一种将字符串中的一部分(通常以 `{}` 标记)以外部数据(比如变量值或者其他字符串)替换的方法。- 方法 `x.format()` 在任何版本的 Python 3 中受到支持- 带有前缀 f 的格式化字符串(即 f-string 或 f 字符串)在 Python 3.6 开始被支持字符串还有一种以百分号 `%` 进行格式化的方法,是从 Python 2 时期延续下来的语法(在 Python 3 中也可以使用)。本文不再介绍这部分内容,有兴趣的读者可以自行查阅。 我们常常需要把变量的值(可能不是字符串类型)嵌入到字符串中,比如: | lang, ver = "Python", 3
x = "We are learning " + lang + " " + str(ver) + "."
print(x) | We are learning Python 3.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
上例中虽然用加法连接实现了这一点,但的确非常狼狈。 format() 方法Python 支持用 `x.format()` 的形式来格式化字符串: | lang, ver = "Python", 3
x = "We are learning {} {}.".format(lang, ver)
# 也可以按名称访问
y = "We are learning {mylang} {myver}.".format(mylang=lang, myver=ver)
# 甚至可以进行字典展开,参考字典章节
d = {"mylang": lang, "myver": ver}
z = "We are learning {mylang} {myver}.".format(**d)
print(x, x==y, x==z, sep='\n') | We are learning Python 3.
True
True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
上面的几种写法都可以得到相同的结果。如你所见,在格式化字符串中,我们用花括号来占位。默认的, `x.format()` 的输入参数都会被转为字符串格式。- 如果要在格式化字符串中打印花括号,请使用双写花括号(比如 `{{` )。- 如果传入的参数是键值对(即 `key=value` 的形式),请在花括号内注明键名称。这样的优势是代码可读性好。利用重复的键名或者重复的序号,可以反复使用同一个目标: | # 复用 lang 变量
x = "We are learning {0} {1}. I love {0}!".format(lang, ver)
y = "We are learning {mylang} {myver}. I love {mylang}!".format(mylang=lang, myver=ver)
print(x, x==y, sep='\n') | We are learning Python 3. I love Python!
True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
一个更复杂的例子是将输入参数转为特定的字符串格式,比如将浮点数转换为保留指定小数位的字符串。这时候需要用到冒号 `:` 来指定格式——格式指定位于冒号右侧,而键名(如果无则留空)位于冒号左侧: | val, digits = 3.1415926535, 5
x = "PI = {:.5f}...".format(val)
y = "PI = {val:.5f}...".format(val=val)
z = "PI = {0:.{1}f}...".format(val, digits)
print(x, x==y, x==z, sep='\n') | PI = 3.14159...
True
True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
Python 支持的格式有:| 格式声明 | 格式示例 | 解释 | 输入 | 输出 || :--- | :---: | :--- | :--- | :--- || `s` | `{:5s}` | 字符串,以最小宽5位输出 | `"abc"` | " abc" || 任意数 | | `e` | `{:.2e}` | 科学计数法小数点后2位(默认6) | `1234.567` | "1.23e+03" || `E` | / | 同上,但输出时大写字母 E | `1234.567` | "1.23E+03" || `f` | `{:.4f}` | 保留小数点后4位(默认6) | `1234.567` | "1234.5670" ||... | # 在数字两侧各添加3个星号
x = 1234
print("{:*^{}d}".format(x, len(str(x))+6))
# 输入给定十进制数的其他进制形式
x = 123
for base in "dboxX":
print("Type {base}: {val:#{base}}".format(base=base, val=x)) | Type d: 123
Type b: 0b1111011
Type o: 0o173
Type x: 0x7b
Type X: 0X7B
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
f 字符串上面的例子均由 `x.format()` 方法实现,但是不足之处在于不能方便地直接利用已有的变量值。比如上文中给浮点数保留指定位数的例子,变量 `val` 与 `digits` 仍然需要显式地作为 `format()` 方法的输入参数: | val, digits = 3.1415926535, 5
x = "PI = {0:.{1}f}...".format(val, digits)
y = "PI = {myval:.{mydigits}f}...".format(myval=val, mydigits=digits)
print(x, x==y, sep='\n') | PI = 3.14159...
True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
当然,采用上文所介绍过字典展开的方式,你可以用先声明一个字典,然后在传入时用双写星号前缀来展开…… | val, digits = 3.1415926535, 5
d = {"myval": val, "mydigits": digits}
x = "PI = {myval:.{mydigits}f}...".format(**d)
print(x) | PI = 3.14159...
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
这样, `x.format()` 方法的输入就显得不是太累赘。但并不是所有数据都适合写入同一个字典里的。因此,我推荐使用更方便的 f 字符串来格式化字符串,在字符串的左侧引号之前添加字母 f 即可: | # Python >= 3.6
val, digits = 3.1415926535, 5
x = f"PI = {val:.{digits}f}..."
print(x) | PI = 3.14159...
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
与 `x.format()` 方法一样,f 字符串支持格式化字串的所有格式。f 字符串也允许在花括号内进行合法的 Python 表达式书写: | print(f"{2**3:0>4d}") | 0008
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
但是,花括号中的表达式不能显示地含有反斜线: | print(f"A multiline string:\n{'a'+'\n'+'b'}") | _____no_output_____ | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
你可以通过将带反斜线的值赋值到变量来规避这一点: | x = "{}\n{}".format('a', 'b')
print(f"A multiline string:\n{x}") | A multiline string:
a
b
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
大小写转换\*Python 提供了丰富的大小写转换支持,包括- 全体强制大小写 `upper()/lower()`- 仅首字母大写 `capitalize()`- 每个单词首字母大写 `title()` | x = "It's a string. This is another."
n = len(x) + 10
d = {
"全大写": x.upper(),
"全小写": x.lower(),
"首字母大写": x.capitalize(),
"单词首字母大写": x.title()
}
for k, v in d.items():
print(f"{k:10}\t{v}") | 全大写 IT'S A STRING. THIS IS ANOTHER.
全小写 it's a string. this is another.
首字母大写 It's a string. this is another.
单词首字母大写 It'S A String. This Is Another.
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
注意, `title()` 方法会将一些并非单词头的字母识别为单词头(比如上例中 `It's` 的字母 s)。要避免这一情形,可以配合正则表达式处理,参考 [官方文档:str.title()](https://docs.python.org/zh-cn/3/library/stdtypes.html?highlight=splitstr.title) 。 字典:dictPython 的字典以键值对(key-value pairs)的形式存储数据:- 每一项数据之间用逗号 `,` 分隔,所有数据外侧用一组花括号 `{}` 包裹- 每一项数据都是一组键值对,键与值之间用冒号 `:` 分隔- 一个字典内,不能存在相同的键名- 在 Pyt... | x = {} # 空字典
y = {"a": 1, "b": 3}
print(y) | {'a': 1, 'b': 3}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字典的每一项数据的值可以是任意的数据类型。同时,不同于 JSON 文件中的键,Python 字典的键也可以是大多数类型(而不仅仅是字符串)。*从编程习惯上讲,我并不推荐在字典键中使用字符串以外的其他类型。*字典可以用 `len()` 来返回其键值对的个数,用 `in` 来查询一个键是否在字典中: | x = {}
print(len(x))
print("a" in x) | 0
False
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字典初始化字典有许多初始化方式。- 依次添加键值对- 利用 `dict()` 构造 - 从成对序列数据中构造 - 显式地传入字面键值- 利用 `fromkeys()` 方法- 字典解析最朴素的方式是依次添加键值对。先新建一个空字典,然后依次向内添加键值对: | d = {}
d["a"] = 1
d["c"] = 3
d["b"] = 2
print(d) | {'a': 1, 'c': 3, 'b': 2}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
在键与值分别存储在两个序列中时,我们可以利用 for 循环: | keys = "a", "c", "b"
vals = 1, 3, 2
d = {}
for k, v in zip(keys, vals):
d[k] = v
print(d) | {'a': 1, 'c': 3, 'b': 2}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
从成对序列数据中构造要求一种整合的数据存储方式。如果键与值是“成对地”存储在一个序列中,可以直接使用 `dict()` 来进行初始化: | data = [["a", 1], ["c", 3], ["b", 2]]
d = dict(data)
print(d) | {'a': 1, 'c': 3, 'b': 2}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
在字典数据不多时,也可能考虑显式地传入字面键值(键自动视为字符串): | d = dict(a=1, c=3, b=2)
print(d) | {'a': 1, 'c': 3, 'b': 2}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
使用 `fromkeys()` 方法能够快速初始化已知键名的字典,将所有键都赋同一个初始值(比如 `None` ): | keys = "a", "c", "b"
d = {}.fromkeys(keys, None)
print(d) | {'a': None, 'c': None, 'b': None}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
类似于列表解析,字典也支持解析: | data = [["a", 1], ["c", 3], ["b", 2]]
d1 = {x[0]: x[1] for x in data}
keys = "a", "c", "b"
vals = 1, 3, 2
d2 = {k: v for k, v in zip(keys, vals)}
print(d1, d1==d2) | {'a': 1, 'c': 3, 'b': 2} True
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字典的视图由于字典有键、值、项(键值对)这三个概念,Python 也提供了对应的三种视图:- 键视图: `x.keys()` ,一个依序的、每个键为一个元素的序列- 值视图: `x.values()` ,一个与键视图中的键依次对应的值组成的序列- 项视图: `x.items()` ,一个依上述顺序的、每个元素是一个键值对元组的序列用 for 循环来展示一下这三种视图: | x = {"a": 1, "c": 3}
for k in x.keys():
print(f"key: {k}")
for v in x.values():
print(f"val: {v}")
for i in x.items():
print(f"item: {i}") | key: a
key: c
val: 1
val: 3
item: ('a', 1)
item: ('c', 3)
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
在 `x.keys()` 中循环其实与在 `x` 中循环的结果是相同的,都是遍历字典的键: | for k in x:
print(k) | a
c
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字典的项视图 `items()` 常常被用在 for 循环中,解包成两个循环变量: | x = {"a": 1, "c": 3}
for k, v in x.items():
print(f"{k} = {v}") | a = 1
c = 3
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
按键索引值:get() / setdefault()要按字典键索引其对应的值,有以下几种方法:- 如果确认键 key 位于字典 x 中,可以直接使用该键来索引 `x[key]`- 如果键 key 可能不在 x 中: - 用 `x.get(key, default=None)` 方法,失败时它会返回一个备用值 `default` - 用 `x.setdefault(key, default=None)` 方法,失败时它会把键值对 `key: default` 添加到字典 | x = {"a": 1, "c": 3}
print(x["a"]) | 1
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
更安全的选择是使用 `x.get(key, default=None)` 方法。它的作用是:如果 key 存在于 x 的键中,那么返回该键对应的值;否则,返回 default 指定的值。 | x = {"a": 1, "c": 3}
print(x.get("b", "Not in dict")) | Not in dict
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
另一个选择是利用 `x.setdefault(key, default=None)` 方法。如果 key 存在于 x 的键中,那么返回该键对应的值;否则,将 default 值与 key 键组成键值对,加入到字典 x 中。 | x = {"a": 1, "c": 3}
y1 = x.setdefault("b", 2)
y2 = x["b"] # 键值对已经被添加
print(y1, y2) | 2 2
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
删除项:pop() / popitem()最简单的自然是 `del()` 删除函数: | x = {"a": 1, "c": 3, "b": 2}
del(x["a"])
print(x) | {'c': 3, 'b': 2}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
字典的 `x.pop(key)` 与列表在表现上类似,也是返回一个值的同时将其从容器中删除: | x = {"a": 1, "c": 3, "b": 2}
y = x.pop("a")
print(x, y) | {'c': 3, 'b': 2} 1
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
特别指出,方法 `pop()` 也有一个名为 `default` 的参数,会在字典不包含键时返回该 default 值(如果不显示地给出 default 的值,那么会造成 KeyError)。这一点与 `setdefault()` 方法相映成趣。 | x = {"a": 1, "c": 3, "b": 2}
y = x.pop("a", 10) # 正常返回 x["a"],并删除键 "a"
z = x.pop("a", 100) # 没有键 "a",返回默认值 100
print(x, y, z) | {'c': 3, 'b': 2} 1 100
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
最后,介绍 `popitem()` ,这个方法被用到的较少。它并不指定键名来抛出一个项,而是按照字典键的顺序,反向地依次抛出字典地项——即后进先出(LIFO),如同对栈容器进行弹栈操作一样。*对于 Python 3.7 之前的版本,它并不是依照 LIFO 顺序弹出字典项的,而是按照随机选择的顺序。* | x = {"a": 1, "c": 3, "b": 2}
while len(x) > 0:
y = x.popitem()
print(y) | ('b', 2)
('c', 3)
('a', 1)
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
更新字典:update()通过 `x.update(y)` ,字典 x 可以根据字典 y 的键值对来就地更新字典 x 的数据:- 在字典 x 与 y 中都存在的键,以 y 中的值为准- 仅在一个字典中存在的键,得以保留 | x = {"a": 1, "c": 3, "b": 2}
y = {"a": -10, "d": 4}
x.update(y)
print(x) | {'a': -10, 'c': 3, 'b': 2, 'd': 4}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
利用循环,我们可以实现与 `update()` 方法相同的效果: | x = {"a": 1, "c": 3, "b": 2}
y = {"a": -10, "d": 4}
for k in y:
x[k] = y[k]
print(x) | {'a': -10, 'c': 3, 'b': 2, 'd': 4}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
更改键名\*字典并没有单独提供更改键名的方法,但这也是一个实用场景。由于 Python >= 3.7 版本引入了字典键的顺序,要在更改键名时保持键的顺序也显得重要。先说明一种会打乱键顺序的键名更改方法,那就是将指定键用 `pop(oldkey)` 弹出然后赋值给 `d[newkey]` 。下面以将键名改为小写为例: | d = dict(a=1, B=2, c=3, D=4)
dkey = dict(B="b", D="d")
for oldkey, newkey in dkey.items():
d[newkey] = d.pop(oldkey)
print(d) | {'a': 1, 'c': 3, 'b': 2, 'd': 4}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
可以看到,字典 d 的键顺序也被打乱了。要保留顺序,只能遍历所有的字典键: | d = {"a": 1, "B": 2, "c": 3, "D": 4}
dkey = {"B": "b", "D": "d"}
oldkeys = tuple(d.keys())
for k in oldkeys:
# 如果有新键名则使用 dkey[k],否则使用旧键名 k
d[dkey.get(k, k)] = d.pop(k)
print(d) | {'a': 1, 'b': 2, 'c': 3, 'd': 4}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
集合Python 中的集合借鉴了数学意义上的集合概念,要求内部的元素不能重复。- 集合 set 是可变的;Python 也提供了一种不可变集合 frozenset ,其不涉及可变性部分的用法与 set 大致相同。集合用花括号括起的、逗号分隔的多个项来表示。但是,空集合不能使用 `{}` 来指明(因为这代表空字典),请使用 `set()` 指明。 | x = set([1, 2, 3, 2])
y = {1, 2, 3}
z = set() # 空集合
print(x, y, z) | {1, 2, 3} {1, 2, 3} set()
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
集合同样支持长度度量 `len()` ,包含性检查 `in` ,以及循环遍历。 | x = {1, 2, 3}
print(len(x), 4 in x)
for k in x:
print(k, end=' ') | 3 False
1 2 3 | MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
集合运算与包含关系集合运算包括交集、并集、差集、对称差集,包含关系包括(真)子集、(真)超集。| 运算 | 说明 | 运算符 | 示例 | 集合方法 | 示例 || --- | --- | --- | :--- | :--- | :--- || 交 | `&` | `a & b` | 同时位于两个集合中的元素 | `intersection` | `a.intersection(b, c, ...)` || 并 | `\|` | `a \| b` | 至少位于其一集合中的元素 | `union` | `a.union(b,c, ...)` || 差 | `-` | `a - b` | 只位于 a 而不位于 b 的元素 | `dif... | a, b = {1, 2, 3}, {2, 4, 5}
set_funcs = {
"交": set.intersection,
"并": set.union,
"差": set.difference,
"对称差": set.symmetric_difference,
"子集": set.issubset,
"超集": set.issuperset,
"互斥": set.isdisjoint
}
for text, func in set_funcs.items():
print(f"{text:8}\t{func(a, b)}") | 交 {2}
并 {1, 2, 3, 4, 5}
差 {1, 3}
对称差 {1, 3, 4, 5}
子集 False
超集 False
互斥 False
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
更新集合集合的更新是就地更新,也涉及到上面的集合运算:- 直接更新 `a.update(b, ...)` ,即将并集赋回,等同于 `a |= b | ...`- 只保留交集 `a.intersection_update(b, ...)` ,即将交集赋回,等同于 `a &= b & ...`- 只保留差集 `a.difference_update(b, ...)` ,等同于 `a -= b | ...`- 只保留对称差集 `a.symmetric_difference_update(b)` ,等同于 `a ^= b`以上命令中,除了对称差以外的运算都可以输入多个集合。 | a, b = {1, 2, 3}, {2, 4, 5}
set_funcs = {
"(并)更新": set.update,
"交更新": set.intersection_update,
"差更新": set.difference_update,
"对称差更新": set.symmetric_difference_update
}
for text, func in set_funcs.items():
a_copy = a.copy() # 拷贝一个副本,避免直接对 a 改动
func(a_copy, b)
print(f"{text:8}\t{a_copy}") | (并)更新 {1, 2, 3, 4, 5}
交更新 {2}
差更新 {1, 3}
对称差更新 {1, 3, 4, 5}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
增删元素本节中的命令只对可变集合(set 类型)有效,对不可变集合(frozenset 类型)无效 。- 增加:`add(elem)`- 移除: - 移除指定: - `remove(elem)` :移除一个不存在集合中的元素时会造成 KeyError - `discard(elem)` :尝试移除一个元素,如果不存在集合中则静默 - 随机移除: `pop()` ,随机返回一个集合中的元素,并将其从集合中移除 - 清空: `clear()` | a = {1, 2, 3}
a.add(4)
print("After add\t", a)
a.remove(3)
print("After remove\t", a)
a.discard(100)
print("After discard\t", a) | After add {1, 2, 3, 4}
After remove {1, 2, 4}
After discard {1, 2, 4}
| MIT | docsrc/Python/VariableTypes.ipynb | wklchris/blog |
Multivariate Distributions in PythonSometimes we can get a lot of information about how two variables (or more) relate if we plot them together. This tutorial aims to show how plotting two variables together can give us information that plotting each one separately may miss. | # import the packages we are going to be using
import numpy as np # for getting our distribution
import matplotlib.pyplot as plt # for plotting
import seaborn as sns; sns.set() # For a different plotting theme
# Don't worry so much about what rho is doing here
# Just know if we have a rho of 1 then we will get a perfe... | _____no_output_____ | MIT | Understanding_and_Visualizing_Data_with_Python-master/week3/Multivariate_Distributions.ipynb | rezapci/UofM_Statistics_with_Python_Specialization |
Work with ComputeWhen you run a script as an Azure Machine Learning experiment, you need to define the execution context for the experiment run. The execution context is made up of:* The Python environment for the script, which must include all Python packages used in the script.* The compute target on which the scrip... | import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name)) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Prepare data for an experimentIn this notebook, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if it already exists, the code will find the existing version) | from azureml.core import Dataset
default_ds = ws.get_default_datastore()
if 'diabetes dataset' not in ws.datasets:
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data
target_path='diabetes-data/', # Put it in a folder path... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Create a training scriptRun the following two cells to create:1. A folder for a new experiment2. An training script file that uses **scikit-learn** to train a model and **matplotlib** to plot a ROC curve. | import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_logistic'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
%%writefile $experiment_folder/diabetes_training.py
# Import libraries
import argparse
from azureml.core import Run
import panda... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Define an environmentWhen you run a Python script as an experiment in Azure Machine Learning, a Conda environment is created to define the execution context for the script. Azure Machine Learning provides a default environment that includes many common packages; including the **azureml-defaults** package that contains... | from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
# Create a Python environment for the experiment
diabetes_env = Environment("diabetes-experiment-env")
diabetes_env.python.user_managed_dependencies = False # Let Azure ML manage dependencies
diabetes_env.docker.enabled ... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Now you can use the environment to run a script as an experiment.The following code assigns the environment you created to a ScriptRunConfig, and submits an experiment. As the experiment runs, observe the run details in the widget and in the **azureml_logs/60_control_log.txt** output log, you'll see the conda environme... | from azureml.core import Experiment, ScriptRunConfig, Environment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.widgets import RunDetails
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
The experiment successfully used the environment, which included all of the packages it required - you can view the metrics and outputs from the experiment run in Azure Machine Learning Studio, or by running the code below - including the model trained using **scikit-learn** and the ROC chart image generated using **ma... | # Get logged metrics
metrics = run.get_metrics()
for key in metrics.keys():
print(key, metrics.get(key))
print('\n')
for file in run.get_file_names():
print(file) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Register the environmentHaving gone to the trouble of defining an environment with the packages you need, you can register it in the workspace. | # Register the environment
diabetes_env.register(workspace=ws) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Note that the environment is registered with the name you assigned when you first created it (in this case, *diabetes-experiment-env*).With the environment registered, you can reuse it for any scripts that have the same requirements. For example, let's create a folder and script to train a diabetes model using a differ... | import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_tree'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
%%writefile $experiment_folder/diabetes_training.py
# Import libraries
import argparse
from azureml.core import Run
import pandas as... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Now you can retrieve the registered environment and use it in a new experiment that runs the alternative training script (there is no regularization parameter this time because a Decision Tree classifier doesn't require it). | from azureml.core import Experiment, ScriptRunConfig, Environment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.widgets import RunDetails
# get the registered environment
registered_env = Environment.get(ws, 'diabetes-experiment-env')
# Get the training dataset
diabetes_ds = ws.datasets.g... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
This time the experiment runs more quickly because a matching environment has been cached from the previous run, so it doesn't need to be recreated on the local compute. However, even on a different compute target, the same environment would be created and used - ensuring consistency for your experiment script executio... | # Get logged metrics
metrics = run.get_metrics()
for key in metrics.keys():
print(key, metrics.get(key))
print('\n')
for file in run.get_file_names():
print(file) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
View registered environmentsIn addition to registering your own environments, you can leverage pre-built "curated" environments for common experiment types. The following code lists all registered environments: | from azureml.core import Environment
envs = Environment.list(workspace=ws)
for env in envs:
print("Name",env) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
All curated environments have names that begin ***AzureML-*** (you can't use this prefix for your own environments).Let's explore the curated environments in more depth and see what packages are included in each of them. | for env in envs:
if env.startswith("AzureML"):
print("Name",env)
print("packages", envs[env].python.conda_dependencies.serialize_to_string()) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Create a compute clusterIn many cases, your local compute resources may not be sufficient to process a complex or long-running experiment that needs to process a large volume of data; and you may want to take advantage of the ability to dynamically create and use compute resources in the cloud. Azure Machine Learning ... | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
cluster_name = "your-compute-cluster"
try:
# Check for existing compute target
training_cluster = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing cluster, use it.'... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Run an experiment on remote computeNow you're ready to re-run the experiment you ran previously, but this time on the compute cluster you created. > **Note**: The experiment will take quite a lot longer because a container image must be built with the conda environment, and then the cluster nodes must be started and t... | # Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
arguments = ['--input-data', diabetes_ds.as_named_input('training_data')],
environment=registered_en... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
While you're waiting for the experiment to run, you can check on the status of the compute in the widget above or in [Azure Machine Learning studio](https://ml.azure.com). You can also check the status of the compute using the code below. | cluster_state = training_cluster.get_status()
print(cluster_state.allocation_state, cluster_state.current_node_count) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Note that it will take a while before the status changes from *steady* to *resizing* (now might be a good time to take a coffee break!). To block the kernel until the run completes, run the cell below. | run.wait_for_completion() | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
After the experiment has finished, you can get the metrics and files generated by the experiment run. This time, the files will include logs for building the image and managing the compute. | # Get logged metrics
metrics = run.get_metrics()
for key in metrics.keys():
print(key, metrics.get(key))
print('\n')
for file in run.get_file_names():
print(file) | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
Now you can register the model that was trained by the experiment. | from azureml.core import Model
# Register the model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'Compute cluster'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
# List registered models... | _____no_output_____ | MIT | 07 - Work with Compute.ipynb | HarshKothari21/mslearn-dp100 |
NumerBlox> Solid Numerai pipelines `numerblox` offers Numerai specific functionality, so you can worry less about software/data engineering and focus more on building great Numerai models!Most of the components in this library are designed for solid weekly inference pipelines, but tools like `NumerFrame`, preprocessor... | # hide_input
from rich.console import Console
from rich.tree import Tree
console = Console(record=True, width=100)
tree = Tree(":computer: Directory structure before starting", guide_style="bold bright_black")
model_tree = tree.add(":file_folder: test_assets")
model_tree.add(":page_facing_up: joblib_v2_example_model.... | _____no_output_____ | Apache-2.0 | nbs/index.ipynb | crowdcent/numerblox |
2.2.2. Numerai Signals ```python --- 0. Numerblox dependencies ---from numerblox.download import KaggleDownloaderfrom numerblox.numerframe import create_numerframefrom numerblox.preprocessing import KatsuFeatureGeneratorfrom numerblox.model import SingleModelfrom numerblox.model_pipeline import ModelPipelinefrom numer... | # hide_input
from rich.console import Console
from rich.tree import Tree
console = Console(record=True, width=100)
tree = Tree(":computer: Directory structure before starting", guide_style="bold bright_black")
model_tree = tree.add(":file_folder: test_assets")
models_tree = tree.add(":file_folder: models")
models_tre... | _____no_output_____ | Apache-2.0 | nbs/index.ipynb | crowdcent/numerblox |
3. ContributingBe sure to read `CONTRIBUTING.md` for detailed instructions on contributing.If you have questions or want to discuss new ideas for `numerblox`, check out [rocketchat.numer.ai/channel/numerblox](https://rocketchat.numer.ai/channel/numerblox). 4. Branch structure Every new feature should be implemented i... | # hide_input
console = Console(record=True, width=100)
tree = Tree("Branch structure", guide_style="bold bright_black")
main_tree = tree.add("📦 master (release)", guide_style="bright_black")
dev_tree = main_tree.add("👨💻 dev")
feature_tree = dev_tree.add(":sparkles: feature/ta-signals-features")
dev_tree.add(":spa... | _____no_output_____ | Apache-2.0 | nbs/index.ipynb | crowdcent/numerblox |
5. Crediting sourcesSome of the components in this library may be based on forum posts, notebooks or ideas made public by the Numerai community. We have done our best to ask all parties who posted a specific piece of code for their permission and credit their work in the documentation. If your code is used in this lib... | # hide
# Run this cell to sync all changes with library
from nbdev.export import notebook2script
notebook2script() | Converted 00_misc.ipynb.
Converted 01_download.ipynb.
Converted 02_numerframe.ipynb.
Converted 03_preprocessing.ipynb.
Converted 04_model.ipynb.
Converted 05_postprocessing.ipynb.
Converted 06_modelpipeline.ipynb.
Converted 07_evaluation.ipynb.
Converted 08_key.ipynb.
Converted 09_submission.ipynb.
Converted 10_staking... | Apache-2.0 | nbs/index.ipynb | crowdcent/numerblox |
Analysis of Aire Immuno-fluorescence in thymusby Pu Zheng2021.3.19 | %run "..\..\Startup_py3.py"
sys.path.append(r"..\..\..\..\Documents")
import ImageAnalysis3 as ia
%matplotlib notebook
from ImageAnalysis3 import *
print(os.getpid())
import h5py
from ImageAnalysis3.classes import _allowed_kwds
import ast
data_folder = r'\\10.245.74.158\Chromatin_NAS_5\Thymus_mouse\191017_Th_Aire_CK... | _____no_output_____ | MIT | Immuno_fluorescence_analysis/20210319-Aire_IF_mouse_thymus_analysis.ipynb | shiwei23/Chromatin_Analysis_Scripts |
Movielens | %reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.learner import *
from fastai.column_data import * | _____no_output_____ | Apache-2.0 | courses/dl1/lesson5-movielens_max_playground.ipynb | maxwellmckinnon/fastai_maxfork |
Data available from http://files.grouplens.org/datasets/movielens/ml-latest-small.zip | path='/root/data/ml-latest-small/' | _____no_output_____ | Apache-2.0 | courses/dl1/lesson5-movielens_max_playground.ipynb | maxwellmckinnon/fastai_maxfork |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.