我是python的新手,我想知道如何用一个单词对文本文件进行分组。例如,说我的文本文件如下所示:
eggs monday $5 john
bread monday $3 harry
bananas wednesday $2 john
milk saturday $4 sally
tomatoes sunday $7 sally
在我的情况下,我想按名称对文件进行分组。因此,对于约翰来说,我希望它像这样显示:
[john,[eggs,monday],[bananas,wednesday]]
哈利和莎莉等等。
所以现在我的代码看起来像这样,我已经能够确定必要的东西(即名称,项目和日期),但我对如何将其分组感到困惑。
def grocery():
file = open('shopping.txt')
wholelist = []
innerlist = []
for line in file:
lines = line.split()
name = lines[3]
item = lines[0]
day = lines[1]
提前谢谢你。此外,我仅限于使用列表中的列表,因此我不允许使用词典。
答案 0 :(得分:2)
如果您只限制使用列表,则可以尝试这样的操作:
a ="""eggs monday $5 john
bread monday $3 harry
bananas wednesday $2 john
milk saturday $4 sally
tomatoes sunday $7 sally"""
sents = [b.split() for b in a.splitlines()]
names = []
for s in sents:
if s[3] not in names:
names.append(s[3])
names.append([])
for name in names:
for s in sents:
if name == s[3]:
names[names.index(name)+1].append([s[0], s[1]])
for no in range(0,len(names),2):
print [names[no]] + [a for a in names[no+1]]
输出:
['john', ['eggs', 'monday'], ['bananas', 'wednesday']]
['harry', ['bread', 'monday']]
['sally', ['milk', 'saturday'], ['tomatoes', 'sunday']]
答案 1 :(得分:0)
如果不限于使用列表和词典,我建议使用PythoN Data AnalysiS library(pandas)表示具有不同字段类型的表格数据。
它会像这样
import pandas as pd
df = pd.read_table('data.txt', names=['item', 'day', 'price', 'name'],
delim_whitespace=True)
for name, group in df.groupby('name'):
print name, ':'
print group[['item','day']]
输出
harry :
item day
1 bread monday
john :
item day
0 eggs monday
2 bananas wednesday
sally :
item day
3 milk saturday
4 tomatoes sunday
如果您仅限于使用评论中指明的列表,我会使用.index()
list
对象的方法:
table = [line.strip().split() for line in lines] # strip the newline char
table = [row for row in table if len(row) > 0] # remove empty lines
names = [] # for keeping names
groups = [] # for keeping groups associeated to names
for row in table:
item, day, price, day = row
try:
i = names.index(name)
except ValueError:
names.append(name)
i = len(names) - 1
groups.append([])
groups[i].append([item, day])
result = list(zip(names, groups))
答案 2 :(得分:-1)
试试这个
from collections import defaultdict
def grocery():
wholelist = defaultdict(list)
with open('shopping.txt') as file:
for line in file:
lines = line.split()
wholelist[lines[3]].append(lines[0:2])
return wholelist
custom_list = [[key]+val for key,val in grocery().items()]
print (sorted(custom_list,key=lambda data:data[0]))
custom_list
具有您想要的格式
答案 3 :(得分:-1)
with open('shopping.txt') as file:
d = defaultdict(list)
for line in file:
lines = line.split()
print(lines)
name = lines[3]
item = lines[0]
day = lines[1]
d[name].append([item, day])
出:
defaultdict(list,
{'harry': [['bread', 'monday']],
'john': [['eggs', 'monday'], ['bananas', 'wednesday']],
'sally': [['milk', 'saturday'], ['tomatoes', 'sunday']]})