python處理數據一些小tips

str.split(separator, maxsplit)

separator : The is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.

maxsplit : It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then there is no limit.

format 格式化函數

格式化字符串 

基本語法是通過 {} 和 : 來代替以前的 % 。

format 函數可以接受不限個參數,位置可以不按順序。

>>>"{} {}".format("hello", "world")    # 不設置指定位置,按默認順序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 設置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 設置指定位置
'world hello world'

也可以設置參數:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
 
# 通過字典設置參數
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))
 
# 通過列表索引設置參數
my_list = ['菜鳥教程', 'www.runoob.com']
print("網站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必須的

字典遍歷 使用迭代器 

for i, (k, v) in enumerate(mydict.items()):
    # your stuff
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
    print("index: {}, key: {}, value: {}".format(i, k, v))

# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b

 解釋:

  • enumerate returns an iterator object which contains tuples in the format: [(index, list_element), ...]
  • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...]
  • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章