[英]read file into list separating values
I'm working separating values and keys from a file.So if the word exist in the file add the value to the list. 我正在从文件中分离值和键,因此如果文件中存在单词,则将值添加到列表中。 Is it maybe more efficient to use a dictionary and add the values and keys?
使用字典并添加值和键是否更有效? In the text.txt looks like this:
在text.txt中看起来像这样:
eggs=2, bread=1, milk=4
eggs=5, bread=2, milk=2
eggs=1, bread=3, milk=3
I want to split the values and keys into separate lists so i can later use this to calculate number of eggs 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
We could use itertools.groupby here and by creating a list that holds dictionaries of each line 我们可以在这里使用itertools.groupby ,并创建一个包含每行字典的列表
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
Another method would be to use defaultdict here to setup some dictionaries that will store the information from the text file in a organized fashion where you can access it and manipulate easier down the road 另一种方法是在此处使用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
Working method with keys
holding no value: 没有值的
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])
You can read the file into a dict of lists with dict comprehension: 您可以使用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))}
so that given your sample input from the file object f
, the above would return: 因此,鉴于您从文件对象
f
输入了示例输入,以上代码将返回:
{'eggs': ['2', '5', '1'], 'bread': ['1', '2', '3'], 'milk': ['4 ', '2', '3']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.