尝试从Excel中获取子集

我正在努力编写一个简单的程序,只是努力做到这一点,因为我正在学习Python。

我有一个xlsx。 它的格式是:

Team, Player 

我想要做的是在球场上应用一个filter,然后从每个球队随机抽取10名球员。

我是这样开始的:

 import xlrd # First open the workbook wb = xlrd.open_workbook('C:\Users\ADMIN\Desktop\1.xlsx') # Then select the sheet. sheet = wb.sheet_by_name('Sheet_1') # Then get values of each column. Excuse first item which is header so skip that team = sheet.col_values(0)[1:] players = sheet.col_values(1)[1:] 

不过,我有点在这里继续下去。

任何人都可以提供任何意见/build议吗?

您可以构build由其值为这些团队中玩家列表的团队键入的字典,然后从这些列表中抽样:

 import random teams = {} for t,p in zip(team,players): if t in teams: teams[t].append(p) else: teams[t] = [p] samples = [random.sample(teams[t],10) for t in teams] 

你可以使用filterfunction来做到这一点 –

 filtered_teams = filter(lambda x: x[0] > 2, zip(team, players)) 

你可以用你自己的filter代替lambda x: x[0] > 2 ,在这里检查x [0](或者团队值)是否大于2。

现在假设玩家本身就是一个列表,你可以迭代filtered_teams

 import random print '\n'.join([random.sample(players, 10) for _, players in filtered_teams]) 

这是没有使用任何外部库,但你一定会使用pandas更好的performance。