我正在从文件中分离值和键。因此,如果文件中存在单词,则将值添加到列表中。使用字典并添加值和键是否更有效? 在text.txt中如下所示:
eggs=2, bread=1, milk=4
eggs=5, bread=2, milk=2
eggs=1, bread=3, milk=3
我想将值和键拆分为单独的列表,以便以后可以使用它来计算ect的卵数
egg_list =[]
with open("text.txt") as f:
for line in f:
lines = f.read().splitlines()# creates a list of the file
lines.split("=") # or split on ","?
if "eggs" in line: # checks if the string "eggs" exists in the list
#if so add the value after"=" into the list
egg_list.append(lines[0]+1)#should list 2,5,1
if "bread" #same for bread ect
答案 0 :(得分:1)
我们可以在此处使用 itertools.groupby 并创建一个 list 来保存每行的 dictionary
from itertools import groupby
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
content = [i.split(',') for i in content]
lista = []
for i in content:
lista.append(dict([j.split('=') for j in i]))
total_eggs= sum([int(k) for k, g in groupby(lista, key=lambda x: x['eggs'])])
print(lista)
# [{'eggs': '2', ' bread': '1', ' milk': '4'}, {'eggs': '5', ' bread': '2', ' milk': '2'}, {'eggs': '1', ' bread': '3', ' milk': '3'}]
print(total_eggs)
# 8
另一种方法是在此处使用 defaultdict 来设置一些字典,这些字典将以有组织的方式存储文本文件中的信息,您可以在其中进行访问并轻松地进行操作
from collections import defaultdict
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
dd = defaultdict()
content = [i.split(',') for i in content]
for i, v in enumerate(content):
dd[i] = dict([j.split('=') for j in v])
print(dd)
# {0: {'eggs': '2', ' bread': '1', ' milk': '4'}, 1: {'eggs': '5', ' bread': '2', ' milk': '2'}, 2: {'eggs': '1', ' bread': '3', ' milk': '3'}})
print(sum([int(dd[k]['eggs']) for k in dd]))
# 8
keys
无值的工作方法:
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
content = [i.split(',') for i in content]
lista = []
for i in content:
for j in i:
if len(j.split('=')) > 1:
lista.append({j.split('=')[0]: j.split('=')[1]})
else:
lista.append({j: 0})
total_eggs = sum([int(v) for i in lista for k, v in i.items() if 'eggs' in k])
答案 1 :(得分:0)
您可以使用dict理解将文件读入列表的dict中:
{g[0][0]: [v for _, v in g] for g in zip(*([t.split('=') for t in l.split(', ')] for l in f))}
因此,根据您从文件对象f
输入的示例,以上内容将返回:
{'eggs': ['2', '5', '1'], 'bread': ['1', '2', '3'], 'milk': ['4 ', '2', '3']}