循环浏览一个列表,并将项目追加到一组三个列表,一个接一个



我正在循环访问一个csv.reader((对象以访问原始CSV文件中的18行中的每一行(每行都有关于足球运动员的信息(,然后需要从这些条目中组成三支新的6人团队。它把我的大脑打了一个结;有没有办法使用 for 循环来实现这一点?比如,我怎样才能循环浏览一个列表,然后将第一个项目循环附加到团队 1,第二个项目循环附加到团队 2,依此类推?我已经从三个列表中的列表中使用了 random.choice((,但是使用 if 和 while 语句将每个列表减少到 6 个条目,这给了我奇怪的结果。

不知道它会有多大帮助,但这是我到目前为止所拥有的:

import csv
import random
team1 = []
team2 = []
team3 = []
teamlists = [team1, team2, team3]
with open('soccer_players.csv') as csv_file:
    player_reader = csv.reader(csv_file, delimiter=',')
    for line in player_reader:
        rando = random.choice(teamlists)
        rando.append(line)
        # Need to fill up team1, team2, team3 equally.

这是我正在使用的 CSV 文件:

Name,Height (inches),Soccer Experience,Guardian Name(s)
Joe Smith,42,YES,Jim and Jan Smith
Jill Tanner,36,YES,Clara Tanner
Bill Bon,43,YES,Sara and Jenny Bon
Eva Gordon,45,NO,Wendy and Mike Gordon
Matt Gill,40,NO,Charles and Sylvia Gill
Kimmy Stein,41,NO,Bill and Hillary Stein
Sammy Adams,45,NO,Jeff Adams
Karl Saygan,42,YES,Heather Bledsoe
Suzane Greenberg,44,YES,Henrietta Dumas
Sal Dali,41,NO,Gala Dali
Joe Kavalier,39,NO,Sam and Elaine Kavalier
Ben Finkelstein,44,NO,Aaron and Jill Finkelstein
Diego Soto,41,YES,Robin and Sarika Soto
Chloe Alaska,47,NO,David and Jamie Alaska
Arnold Willis,43,NO,Claire Willis
Phillip Helm,44,YES,Thomas Helm and Eva Jones
Les Clay,42,YES,Wynonna Brown
Herschel Krustofski,45,YES,Hyman and Rachel Krustofski

我不会像你试图做的那样使用循环来创建团队。

相反,如果你先将所有球员读到一个列表中,打乱该列表,那么只需将其切成三份即可创建球队列表。这种方法还可以相对容易地将洗牌的球员名单划分为不同数量的球队。

下面说明了如何执行此操作:

import csv
import random
with open('soccer_players.csv') as csv_file:
    next(csv_file)  # skip header row
    players = [row[0] for row in csv.reader(csv_file, delimiter=',')]
random.shuffle(players)
team1, team2, team3 = [players[i::3] for i in range(3)]
# display results
for i, team in enumerate([team1, team2, team3], 1):
    print('team{}: {}'.format(i, team))

输出:

team1: ['Chloe Alaska', 'Ben Finkelstein', 'Phillip Helm', 'Joe Smith', 'Kimmy Stein', 'Arnold Willis']
team2: ['Matt Gill', 'Jill Tanner', 'Diego Soto', 'Les Clay', 'Herschel Krustofski', 'Bill Bon']
team3: ['Joe Kavalier', 'Karl Saygan', 'Eva Gordon', 'Sammy Adams', 'Sal Dali', 'Suzane Greenberg']

首先,输入文件中有一个标题行,因此必须跳过它。

然后,第一个想法是只选择第一列(名称(以附加到随机选择的列表中,并random.choice(teamlists)

但它可能不会像这样平均地分配值,因为这样或那样的子列表可能比其他子列表更频繁地被选择。

为了获得有保证的均匀分布(当然,前提是名称列表可以除以 3(,我会这样做:

teams = [[] for _ in range(3)]
with open('soccer_players.csv') as csv_file:
    player_reader = csv.reader(csv_file, delimiter=',')
    next(player_reader) # skip title line
    names = [line[0] for line in player_reader]
    random.shuffle(names)
    for i,n in enumerate(names):
        teams[i%len(teams)].append(n)

names是玩家姓名列表。 使用random.shuffle随机更改顺序。然后使用带有模的简单循环来调度值。

此脚本将创建一个包含键号的字典(从 0 到 n,其中 n 是最后一个团队(,并值一个名称列表:

我没有使用随机方法,因为它可以创建稍微不平衡的列表

import csv
team1 = []
team2 = []
team3 = []
teamlists = [team1, team2, team3]
with open('/home/dan/Downloads/test.csv') as csv_file:
    next(csv_file) # to skip header
    player_reader = csv.reader(csv_file, delimiter=',')
    team_index = 0
    for line in player_reader:
        current_list_number = team_index % 3
        teamlists[current_list_number].append(line[0])
        team_index += 1
print teamlists
# will output:
# [['Joe Smith', 'Eva Gordon', 'Sammy Adams', 'Sal Dali', 'Diego Soto', 'Phillip Helm'], ['Jill Tanner', 'Matt Gill', 'Karl Saygan', 'Joe Kavalier', 'Chloe Alaska', 'Les Clay'], ['Bill Bon', 'Kimmy Stein', 'Suzane Greenberg', 'Ben Finkelstein', 'Arnold Willis', 'Herschel Krustofski']]

您可以平均填写 3 个列表(前提是 csv 的数据可被 3 整除(,如下所示:

import csv
import random
team1 = []
team2 = []
team3 = []
teamlists = [team1, team2, team3]
with open('soccer_players.csv') as csv_file:
    player_reader = csv.reader(csv_file, delimiter=',')
    next(player_reader, None)  # skip the headers

    for idx,line in enumerate(player_reader):
        if idx % 3 == 0:
            team1.append(line)
        elif idx % 3 == 1:
            team2.append(line)
        if idx % 3 == 2:
            team3.append(line)
print "team1 = {}".format(team1)
print "----------------------------------------"
print "team2 = {}".format(team2)
print "----------------------------------------"
print "team3 = {}".format(team3) 

输出:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
team1 = [['Joe Smith', '42', 'YES', 'Jim and Jan Smith'], ['Eva Gordon', '45', 'NO', 'Wendy and Mike Gordon'], ['Sammy Adams', '45', 'NO', 'Jeff Adams'], ['Sal Dali', '41', 'NO', 'Gala Dali'], ['Diego Soto', '41', 'YES', 'Robin and Sarika Soto'], ['Phillip Helm', '44', 'YES', 'Thomas Helm and Eva Jones']]
----------------------------------------
team2 = [['Jill Tanner', '36', 'YES', 'Clara Tanner'], ['Matt Gill', '40', 'NO', 'Charles and Sylvia Gill'], ['Karl Saygan', '42', 'YES', 'Heather Bledsoe'], ['Joe Kavalier', '39', 'NO', 'Sam and Elaine Kavalier'], ['Chloe Alaska', '47', 'NO', 'David and Jamie Alaska'], ['Les Clay', '42', 'YES', 'Wynonna Brown']]
----------------------------------------
team3 = [['Bill Bon', '43', 'YES', 'Sara and Jenny Bon'], ['Kimmy Stein', '41', 'NO', 'Bill and Hillary Stein'], ['Suzane Greenberg', '44', 'YES', 'Henrietta Dumas'], ['Ben Finkelstein', '44', 'NO', 'Aaron and Jill Finkelstein'], ['Arnold Willis', '43', 'NO', 'Claire Willis'], ['Herschel Krustofski', '45', 'YES', 'Hyman and Rachel Krustofski']]
>>> len(team1)
6
>>> len(team2)
6
>>> len(team3)
6

相关内容

  • 没有找到相关文章

最新更新