内部固定装置.txt是下赛季英超联赛赛程的内容。数据如下所示:
foo@ubuntu:~/Desktop$ less fixtures.txt |head -n 4
8 August 2015
AFC Bournemouth v Aston Villa #BOUAVL
Arsenal v West Ham United #ARSWHU
Chelsea v Swansea City #CHESWA
我想给每个队的赛程排序。我的方法看起来很糟糕,包含了一堆行。哪种方法更有效?你知道吗
teams = {'BOU' : 4, 'WAT' : 4, 'LEI' : 4, 'NOR' : 4, 'AVL' : 3, 'SUN' : 3, 'NEW' : 3, 'WBA' : 3, 'STK' : 2, 'SWA' : 2, 'EVE': 2, 'SOU' : 2, 'CPL' : 2, 'TOT': 2, 'ARS' : 1, 'CHE' : 1, 'MUN' : 1, 'LIV' : 1, 'MCI' : 1}
fd = open("fixtures.txt", "r")
for lines in fd:
lines = lines.strip()
matches = lines.split("#")
if "CHE" in lines:
for k,v in teams.items():
if k in matches[1]:
if "CHE" not in k:
print k,v
输出(切尔西的第一场比赛):
SWA 2
MCI 1
WBA 3
EVE 2
ARS 1
NEW 3
SOU 2
...
什么是最好的取决于你需要处理多少数据。在这种情况下,一半的问题是数据检索和打印都是混乱的。除非您处理的是大量数据,否则最好将它们分开。你知道吗
如果数据量很小(少于几百个匹配项),则可以将所有数据读入如下列表:
然后使用另一个函数打印:
一种更有效的方法是使用dict作为临时存储,但我认为这段代码可能更容易阅读。你知道吗
相关问题 更多 >
编程相关推荐