You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

826 lines
15 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. ![Monty Python](web/image_888.jpeg)
  4. Main
  5. ----
  6. ```python
  7. if __name__ == '__main__':
  8. main()
  9. ```
  10. List
  11. ----
  12. ```python
  13. <list>[from_inclusive : to_exclusive : step_size]
  14. <list>.append(<el>)
  15. <list>.extend(<list>)
  16. <list>.sort()
  17. <list>.reverse()
  18. ```
  19. ```python
  20. sum(<list>)
  21. sorted_by_second = sorted(<list>, key=lambda tup: tup[1])
  22. flattened_list = [item for sublist in <list> for item in sublist]
  23. ```
  24. Dictionary
  25. ----------
  26. ```python
  27. <dict>.items()
  28. <dict>.get(key, default)
  29. <dict>.setdefault(key, default)
  30. <dict>.update(<dict>)
  31. ```
  32. ```python
  33. collections.defaultdict(<type>) # Creates a dictionary with default values.
  34. dict(zip(keys, values)) # Initiates a dict from two lists.
  35. {k: v for k, v in <dict>.iteritems() if k in <list>} # Filters a dict by keys.
  36. ```
  37. ### Counter
  38. ```python
  39. >>> from collections import Counter
  40. >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  41. >>> Counter(z)
  42. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  43. ```
  44. Set
  45. ---
  46. ```python
  47. <set> = set()
  48. <set>.add(<el>)
  49. <set>.update(<set>)
  50. <set>.union(<set>)
  51. <set>.intersection(<set>)
  52. <set>.difference(<set>)
  53. ```
  54. ### Frozenset
  55. #### Is hashable and can be used as a key in dictionary:
  56. ```python
  57. <set> = frozenset()
  58. ```
  59. Range
  60. -----
  61. ```python
  62. range(to_exclusive)
  63. range(from_inclusive, to_exclusive)
  64. range(from_inclusive, to_exclusive, step_size)
  65. range(from_inclusive, to_exclusive, -step_size)
  66. ```
  67. Enumerate
  68. ---------
  69. ```python
  70. for i, <el> in enumerate(<collection> [, i_start])
  71. ```
  72. Named Tuple
  73. -----------
  74. ```python
  75. >>> TestResults = collections.namedtuple('TestResults', ['filed', 'attempted'])
  76. >>> a = TestResults(1, attempted=2)
  77. TestResults(filed=1, attempted=2)
  78. >>> a.filed
  79. 1
  80. >>> getattr(a, 'attempted')
  81. 2
  82. ```
  83. Iterator
  84. --------
  85. #### Skips first element:
  86. ```python
  87. next(<iter>)
  88. for element in <iter>:
  89. ...
  90. ```
  91. #### Reads input until it reaches an empty line:
  92. ```python
  93. for line in iter(input, ''):
  94. ...
  95. ```
  96. #### Same, but prints a message every time:
  97. ```python
  98. from functools import partial
  99. for line in iter(partial(input, 'Please enter value'), ''):
  100. ...
  101. ```
  102. Generator
  103. ---------
  104. ```python
  105. def step(start, step):
  106. while True:
  107. yield start
  108. start += step
  109. ```
  110. ```python
  111. stepper = step(10, 2)
  112. next(stepper) # 10 (, 12, 14, ...)
  113. ```
  114. Type
  115. ----
  116. ```python
  117. type(<el>) # <class 'int'>/<class 'str'>/...
  118. ```
  119. ```python
  120. import numbers
  121. isinstance(<el>, numbers.Number)
  122. ```
  123. String
  124. ------
  125. ```python
  126. str.replace(text, old, new)
  127. <str>.isnumeric()
  128. <str>.split(sep=None, maxsplit=-1)
  129. <str>.strip()
  130. <str>.join(<list>)
  131. <str>.startswith(<str>)
  132. ```
  133. ### Print
  134. ```python
  135. print(<el> [, <el>, end='', sep='', file=<file>])
  136. ```
  137. ### Regex
  138. ```python
  139. import re
  140. re.sub(<regex>, new, text, count=0)
  141. re.search(<regex>, text) # Searches for first occurance of pattern.
  142. re.match(<regex>, text) # Searches only at the beginning of the string.
  143. re.findall(<regex>, text)
  144. re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  145. ```
  146. * **_Search_ and _match_ return a 'Match' object. Use '.group()' method on it to get the match.**
  147. * **Parameter 'flags=re.IGNORECASE' can be used with all functions.**
  148. * **Use r'\1' for backreference.**
  149. #### Special Sequences:
  150. ```python
  151. # Use capital letter for negation.
  152. '\d' == '[0-9]' # Digit
  153. '\s' == '[ \t\n\r\f\v]' # Whitespace
  154. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  155. ```
  156. ### Format
  157. ```python
  158. '{}'.format(<el> [, <el>, ...])
  159. ```
  160. ```python
  161. {:min_width} # '<el> '
  162. {:>min_width} # ' <el>'
  163. {:^min_width} # ' <el> '
  164. {:_min_width} # '<el>____'
  165. {:.max_width} # '<e>'
  166. ```
  167. ```python
  168. {:max_width.min_width} # ' <e>'
  169. {:max_width.no_of_decimalsf} # ' 3.14'
  170. ```
  171. ```python
  172. >>> person = {'name': 'Jean-Luc', 'height': 187.1}
  173. >>> '{p[height]:.0f}'.format(p=person)
  174. '187'
  175. ```
  176. #### Or:
  177. ```python
  178. >>> f"{person['height']:.0f}"
  179. '187'
  180. ```
  181. ### Text Wrap
  182. ```python
  183. import textwrap
  184. textwrap.wrap(text, width)
  185. ```
  186. Random
  187. ------
  188. ```python
  189. import random
  190. random.random()
  191. random.randint(from_inclusive, to_inclusive)
  192. random.shuffle(<list>)
  193. ```
  194. Infinity
  195. --------
  196. ```python
  197. float("inf")
  198. ```
  199. Datetime
  200. --------
  201. ```python
  202. import datetime
  203. now = datetime.datetime.now()
  204. now.month # 3
  205. now.strftime('%Y%m%d') # 20180315
  206. now.strftime('%Y%m%d%H%M%S') # 20180315002834
  207. ```
  208. Arguments
  209. ---------
  210. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
  211. ```python
  212. args = (1, 2)
  213. kwargs = {'x': 3, 'y': 4, 'z': 5}
  214. func(*args, **kwargs)
  215. ```
  216. #### Is the same as:
  217. ```python
  218. func(1, 2, x=3, y=4, z=5)
  219. ```
  220. Inline
  221. ------
  222. ### Lambda
  223. ```python
  224. lambda: <return_value>
  225. lambda <argument1>, <argument2>: <return_value>
  226. ```
  227. ### Comprehension
  228. ```python
  229. [i+1 for i in range(10)] # [1, 2, ..., 10]
  230. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  231. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  232. (x+5 for x in range(0, 10)) # (5, 6, ..., 14) -> Generator
  233. ```
  234. ```python
  235. [i+j for i in range(10) for j in range(10)]
  236. ```
  237. #### Is the same as:
  238. ```python
  239. out = []
  240. for i in range(10):
  241. for j in range(10):
  242. out.append(i+j)
  243. ```
  244. ### Map, Filter, Reduce
  245. ```python
  246. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  247. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  248. functools.reduce(lambda sum, x: sum+x, range(10)) # 45
  249. ```
  250. ### Any, All
  251. ```python
  252. any(el[1] for el in <collection>)
  253. ```
  254. ### If - Else
  255. ```python
  256. <expression_if_true> if <condition> else <expression_if_false>
  257. ```
  258. Closure
  259. -------
  260. ```python
  261. def multiply_closure(x):
  262. def wrapped(y):
  263. return x * y
  264. return wrapped
  265. multiply_by_3 = multiply_closure(3)
  266. ```
  267. #### Or:
  268. ```python
  269. from functools import partial
  270. partial(<function>, <argument>)
  271. ```
  272. Decorator
  273. ---------
  274. ```python
  275. @closure_name
  276. def function_that_gets_passed_to_closure():
  277. pass
  278. ```
  279. #### Debugger example:
  280. ```python
  281. from functools import wraps
  282. def debug(func):
  283. @wraps(func) # Needed for metadata copying (func name, ...).
  284. def wrapper(*args, **kwargs):
  285. print(func.__name__)
  286. return func(*args, **kwargs)
  287. return wrapper
  288. @debug
  289. def add(x, y):
  290. return x + y
  291. ```
  292. Class
  293. -----
  294. ```python
  295. class <name>:
  296. def __init__(self, a):
  297. self.a = a
  298. def __repr__(self):
  299. return str({'a': self.a})
  300. def __str__(self):
  301. return str(self.a)
  302. ```
  303. ### Enum
  304. ```python
  305. import enum
  306. class <enum_name>(enum.Enum):
  307. <name1> = <value1>
  308. <name2> = <value2>
  309. <name3> = enum.auto() # Can be used for automatic indexing.
  310. ...
  311. ```
  312. ```python
  313. <enum_name>.<name> # == <enum>
  314. <enum_name>(value) # == <enum>
  315. <enum>.name # == <name>
  316. <enum>.value # == <value>
  317. ```
  318. ```python
  319. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  320. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  321. random.choice(list(<enum_name>)) # == random <enum>
  322. ```
  323. ### Copy
  324. ```python
  325. import copy
  326. copy.copy(<object>)
  327. copy.deepcopy(<object>)
  328. ```
  329. System
  330. ------
  331. ### Arguments
  332. ```python
  333. import sys
  334. sys.argv
  335. ```
  336. ### Read File
  337. ```python
  338. def read_file(filename):
  339. with open(filename, encoding='utf-8') as file:
  340. return file.readlines()
  341. ```
  342. ### Write to File
  343. ```python
  344. def write_to_file(filename, text):
  345. with open(filename, 'w', enconding='utf-8') as file:
  346. file.write(text)
  347. ```
  348. ### Execute Command
  349. ```python
  350. import os
  351. os.popen(<command>).read()
  352. ```
  353. #### Or:
  354. ```python
  355. >>> import subprocess
  356. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  357. >>> a.stdout
  358. b'.\n..\nfile1.txt\nfile2.txt\n'
  359. >>> a.returncode
  360. 0
  361. ```
  362. ### Input
  363. ```python
  364. filename = input('Enter a file name: ')
  365. ```
  366. #### Prints lines until EOF:
  367. ```python
  368. while True:
  369. try:
  370. print(input())
  371. except EOFError:
  372. break
  373. ```
  374. JSON
  375. ----
  376. ```python
  377. import json
  378. ```
  379. ### Serialization
  380. ```python
  381. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  382. <object> = json.loads(<str>)
  383. ```
  384. ### Read File
  385. ```python
  386. def read_json_file(filename):
  387. with open(filename, encoding='utf-8') as file:
  388. return json.load(file)
  389. ```
  390. ### Write to File
  391. ```python
  392. def write_to_json_file(filename, an_object):
  393. with open(filename, 'w', encoding='utf-8') as file:
  394. json.dump(an_object, file, ensure_ascii=False, indent=2)
  395. ```
  396. SQLite
  397. ------
  398. ```python
  399. import sqlite3
  400. db = sqlite3.connect(filename)
  401. ```
  402. ### Read
  403. ```python
  404. cursor = db.execute(<query>)
  405. if cursor:
  406. cursor.fetchall() # Or cursor.fetchone()
  407. db.close()
  408. ```
  409. ### Write
  410. ```python
  411. db.execute(<query>)
  412. db.commit()
  413. ```
  414. Exceptions
  415. ----------
  416. ```python
  417. while True:
  418. try:
  419. x = int(input("Please enter a number: "))
  420. break
  421. except ValueError:
  422. print("Oops! That was no valid number. Try again...")
  423. ```
  424. Threading
  425. ---------
  426. ```python
  427. import threading
  428. ```
  429. ### Thread
  430. ```python
  431. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  432. thread.start()
  433. thread.join()
  434. ```
  435. ### Lock
  436. ```python
  437. lock = threading.Rlock()
  438. lock.acquire()
  439. lock.release()
  440. ```
  441. Itertools
  442. ---------
  443. **Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to the list() function.**
  444. ```python
  445. from itertools import *
  446. ```
  447. ### Chain
  448. ```python
  449. >>> chain([1, 2], range(3, 5))
  450. [1, 2, 3, 4]
  451. ```
  452. ### Combinations
  453. ```python
  454. >>> combinations("abc", 2)
  455. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  456. ```
  457. ### Permutations
  458. ```python
  459. >>> permutations("abc", 2)
  460. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  461. ```
  462. ### Product
  463. ```python
  464. >>> list(product('ab', [1, 2]))
  465. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  466. ```
  467. ### Compress
  468. ```python
  469. >>> compress("abc", [True, 0, 23])
  470. ['a', 'c']
  471. ```
  472. ### Count
  473. ```python
  474. >>> a = count(5, 2)
  475. >>> next(a), next(a)
  476. (5, 7)
  477. ```
  478. ### Cycle
  479. ```python
  480. >>> a = cycle("abc")
  481. >>> [next(a) for _ in range(10)]
  482. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  483. ```
  484. ### Groupby
  485. ```python
  486. >>> a = [{"id": 1, "name": "bob"},
  487. {"id": 2, "name": "bob"},
  488. {"id": 3, "name": "peter"}]
  489. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  490. {'bob': [{'id': 1, 'name': 'bob'},
  491. {'id': 2, 'name': 'bob'}],
  492. 'peter': [{'id': 3, 'name': 'peter'}]}
  493. ```
  494. ### Islice
  495. ```python
  496. islice([1, 2, 3], 1, None)
  497. [2, 3]
  498. ```
  499. ### Ifilter, imap and izip
  500. #### Filter, map and zip functions that return generators instead of iterators.
  501. Introspection and Metaprograming
  502. --------------------------------
  503. **Inspecting code at runtime and code that generates code. You can:**
  504. * **Look at the attributes**
  505. * **Set new attributes**
  506. * **Create functions dynamically**
  507. * **Traverse the parent classes**
  508. * **Change values in the class**
  509. ```python
  510. >>> class B:
  511. ... def __init__(self):
  512. ... self.a= 'sdfsd'
  513. ... self.b = 123324
  514. >>> b = B()
  515. ```
  516. ### Getattr
  517. ```python
  518. >>> getattr(b, 'a')
  519. 'sdfsd'
  520. ```
  521. #### Is the same as:
  522. ```python
  523. B.__getattribute__(b, 'a')
  524. ```
  525. ### Hasattr
  526. ```python
  527. >>> hasattr(b, 'c')
  528. False
  529. ```
  530. ### Setattr
  531. ```python
  532. >>> setattr(b, 'c', 10)
  533. ```
  534. ### Type
  535. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!):**
  536. ```python
  537. type(class_name, parents<tuple>, attributes<dict>)
  538. ```
  539. ```python
  540. >>> BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
  541. >>> b = BB()
  542. ```
  543. ### MetaClass
  544. #### Class that creates class:
  545. ```python
  546. def my_meta_class(name, parents, attrs):
  547. ...
  548. return type(name, parents, attrs)
  549. ```
  550. #### Or:
  551. ```python
  552. class MyMetaClass(type):
  553. def __new__(klass, name, parents, attrs):
  554. ...
  555. return type.__new__(klass, name, parents, attrs)
  556. ```
  557. ### Metaclass Attr
  558. **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type:**
  559. ```python
  560. class BlaBla:
  561. __metaclass__ = Bla
  562. ```
  563. Eval
  564. ----
  565. ```python
  566. import ast
  567. import operator as op
  568. # Supported operators
  569. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  570. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  571. ast.USub: op.neg}
  572. def eval_expr(expr):
  573. return eval_(ast.parse(expr, mode='eval').body)
  574. def eval_(node):
  575. if isinstance(node, ast.Num): # <number>
  576. return node.n
  577. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  578. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  579. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  580. return operators[type(node.op)](eval_(node.operand))
  581. else:
  582. raise TypeError(node)
  583. ```
  584. ```python
  585. >>> eval_expr('2^6')
  586. 4
  587. >>> eval_expr('2**6')
  588. 64
  589. >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  590. -5.0
  591. ```
  592. Libraries
  593. =========
  594. Plot
  595. ----
  596. ```python
  597. from matplotlib import pyplot
  598. pyplot.plot(<data> [, <data>])
  599. pyplot.show()
  600. pyplot.savefig(filename)
  601. ```
  602. Web
  603. ---
  604. ```python
  605. import bottle
  606. import urllib
  607. ```
  608. ### Run
  609. ```python
  610. bottle.run(host='localhost', port=8080)
  611. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  612. ```
  613. ### Static request
  614. ```python
  615. @route('/img/<image>')
  616. def send_image(image):
  617. return static_file(image, 'images/', mimetype='image/png')
  618. ```
  619. ### Dynamic request
  620. ```python
  621. @route('/<sport>')
  622. def send_page(sport):
  623. sport = urllib.parse.unquote(sport).lower()
  624. page = read_file(sport)
  625. return template(page)
  626. ```
  627. ### REST request
  628. ```python
  629. @post('/p/<sport>')
  630. def p_handler(sport):
  631. team = request.forms.get('team')
  632. team = urllib.parse.unquote(team).lower()
  633. db = sqlite3.connect(conf.DB_PATH)
  634. p_h, p_a = get_p(db, sport, team)
  635. db.close()
  636. response.headers['Content-Type'] = 'application/json'
  637. response.headers['Cache-Control'] = 'no-cache'
  638. return json.dumps([p_h, p_a])
  639. ```
  640. Curses
  641. ------
  642. ```python
  643. import curses
  644. def main():
  645. curses.wrapper(draw)
  646. def draw(screen):
  647. screen.clear()
  648. screen.addstr(0, 0, "Press ESC to quit.")
  649. while screen.getch() != 27:
  650. pass
  651. ```
  652. #### Gets char from int:
  653. ```python
  654. chr(<int>)
  655. ```
  656. Profile
  657. -------
  658. #### Times execution of the passed code:
  659. ```python
  660. import timeit
  661. timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
  662. ```
  663. #### Generates a PNG image of call graph and highlights the bottlenecks:
  664. ```python
  665. import pycallgraph
  666. graph = pycallgraph.output.GraphvizOutput()
  667. graph.output_file = get_filename()
  668. with pycallgraph.PyCallGraph(output=graph):
  669. <code_to_be_profiled>
  670. ```
  671. #### Utility code for unique PNG filenames:
  672. ```python
  673. def get_filename():
  674. return "{}-{}.png".format("profile", get_current_datetime_string())
  675. def get_current_datetime_string():
  676. now = datetime.datetime.now()
  677. return get_datetime_string(now)
  678. def get_datetime_string(a_datetime):
  679. return a_datetime.strftime('%Y%m%d%H%M%S')
  680. ```
  681. Audio
  682. -----
  683. #### Saves list of floats of size 0 to 1 to a WAV file:
  684. ```python
  685. import wave, struct
  686. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  687. wf = wave.open(filename, 'wb')
  688. wf.setnchannels(1)
  689. wf.setsampwidth(4)
  690. wf.setframerate(44100)
  691. wf.writeframes(b''.join(frames))
  692. wf.close()
  693. ```