Python 编程技巧

 

  

字典合并

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}

  

反转字符串

name = "George"
name[::-1]

  

从函数返回多个值

def get_a_string():
  a = "George"
  b = "is"
  c = "cool"
  return a, b, c
sentence = get_a_string()
(a, b, c) = sentence

  

同时遍历列表的索引和值

m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
  print('{0}: {1}'.format(index, value))

  

 

列表中出现最多的元素

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

  

检查对象的内存使用情况

import sys
x = 1
print(sys.getsizeof(x))

  

将 dict 转换为 XML

from xml.etree.ElementTree import Element
def dict_to_xml(tag, d):
    '''
    Turn a simple dict of key/value pairs into XML
    '''
    elem = Element(tag)
    for key, val in d.items():
        child = Element(key)
        child.text = str(val)
        elem.append(child)
    return elem

  

posted @ 2020-03-22 23:19  wfpanskxin  阅读(110)  评论(0编辑  收藏  举报