-2
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

谢谢你

4

3 回答 3

1

与其他答案类似

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

for line in file:   
    key, val = line.rstrip().split(',')     
    mydict[key].append(val)
于 2013-11-06T22:38:11.247 回答
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
于 2013-11-06T22:23:37.953 回答
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']
于 2013-11-06T22:31:38.573 回答