如何在python中分隔列表?

时间:2013-11-06 22:19:44

标签: python list token

fruit,apple
fruit,tomato
vegetable,carrot
fruit,pear
vegetable,celery
vegetable,cabbage
vegetable,cauliflower
fruit,banana

我想将这个列表从水果和蔬菜中分离出来

水果

apple 
tomato 
pear 
banana

蔬菜

carrot
celery
cabbage
cauliflower

这是我到目前为止的代码

infile = open("hw16.txt","r")
lines = infile.readlines()
infile.close()

print lines
x = []
y = []
for i in range(0, len(lines)):
    tokens = lines[i].rstrip('\n').split(",")
    x.append(str(tokens[0]))
    y.append(str(tokens[1]))
print  x
print y

谢谢

3 个答案:

答案 0 :(得分:1)

与其他答案类似

mydict = {'fruit' : [], 'vegetable' : []}

for line in file:   
    key, val = line.rstrip().split(',')     
    mydict[key].append(val)

答案 1 :(得分:0)

from collections import defaultdict
catergories = defaultdict(list)
with open("hw16.txt") as f:
  for line in f:
    cat, _, name = line.rstrip().partition(",")
    catergories[cat].append(name)
for cat, values in catergories.iteritems():
  print cat
  for x in values:
    print x
  print

答案 2 :(得分:0)

vegetables = []
fruits = []

for line in file:
    type , name = line.strip().split(',') 
    if type == 'fruit':
        fruits.append(name)
    else:
        vegetables.append(name)

输出:

In [87]: print vegetables
['carrot', 'celery', 'cabbage', 'cauliflower']

In [88]: print fruits
['apple', 'tomato', 'pear', 'banana']