2013年8月12日Python的5個最有價值問題

問:Python怎麼在字典裏刪除值但保留相應的鍵html

答:python

假設3都在值裏,而非鍵
>>> for v in D1.values():
...     if 3 in v:
...         v.remove(3)
...
>>> D1
{'A1': [2], 'C1': [4, 5], 'B1': [3]}

這個代碼還能適用於更多狀況,好比:
>>> D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]}
>>> for k, v in D1.items():
...     D1[k] = filter(lambda x: x!=3, v)
...
>>> D1
{'A1': [2], 'C1': [4, 5], 'B1': []}json

問:Python的TKinter框架怎麼建立實體表app

答:框架

from Tkinter import *
from string import ascii_lowercase
  
class app(Frame):
     def __init__( self , master = None ):
         Frame.__init__( self , master)
         self .grid()
         self .create_widgets()
  
     def create_widgets( self ):
         self .entries = {}
         self .tableheight = 9
         self .tablewidth = 9
         counter = 0
         for row in xrange ( self .tableheight):
             for column in xrange ( self .tablewidth):
                 self .entries[counter] = Entry( self , width = 5 )
                 self .entries[counter].grid(row = row, column = column)
                 counter + = 1
  
prog = app()
prog.master.title( 'Sudoku' )
prog.mainloop()
 
答:
import json
import pandas as pd
  
db = json.loads( open ( 'pruItems.json' , 'r' ).read())
pieces = []
for d in db:
     if d[ 'data' ]:
         df = pd.DataFrame(d[ 'data' ])
         df.columns = [ 'date' , 'bid' , 'ask' ]
         df = df.set_index( 'date' )
         pieces.append(df)
  
df = pd.concat(pieces, axis = 1 , keys = [d[ 'fund' ] for d in db])
  
print df
輸出:
                 TGC               FEF              FAF       
                 bid      ask      bid      ask     bid     ask
date                                                         
18/06/2013  34.8400  34.8400  14.9179  14.9179  6.6780  6.6780
17/06/2013  34.4900  34.4900  14.8712  14.8712  6.6510  6.6570
 
答:
使用.content
>>> from bs4 import BeautifulSoup as BS
>>> html = """<li class="li_dataline2">
...
...
... <b> Expiry date: </b>14/09/2013
...
...
... </li>"""
>>> soup = BS(html)
>>> print soup.find( 'li' , { 'class' : 'li_dataline2' }).contents[ - 1 ].strip()
14 / 09 / 2013
相關文章
相關標籤/搜索