循环遍历一个列表,并将项目一个接一个地附加到一组三个列表中

时间:2017-03-27 20:06:15

标签: python

我循环访问csv.reader()对象以访问原始CSV文件中的18行(每个有关足球运动员的信息)中的每一行,然后需要组成三个新的6队来自这些条目。它把我的大脑打成了一个结;有没有办法使用for循环来完成这个?比如,我如何遍历一个列表,然后将第一个项目循环到team1,第二个项目循环到team2,依此类推?我已经从三个列表的列表中使用了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

4 个答案:

答案 0 :(得分:2)

我不会像你想要的那样使用循环来创建团队。

相反,如果你首先将所有玩家都读入一个列表,然后对该列表进行洗牌,那么只需将其划分为三分即可创建团队列表。这种方法也可以使洗牌球员名单分成不同数量的球队相对容易。

以下说明了如何做到这一点:

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']

答案 1 :(得分:1)

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

然后,第一个想法就是选择第一列(名称)附加到随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随机更改订单。然后使用带模数的简单循环来调度值。

答案 2 :(得分:0)

此脚本将创建一个包含键编号的字典(从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 :(得分:0)

您可以平均填写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