2013年8月12日Python的5个最有价值问题
答:
假设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': []}
答:
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