我正在尝试完成一个项目,将显示年销售总额从一个特定的列表包含在一个.txt文件。
该列表的格式如下:
-lastname, firstname (string)
-45.7 (float)
-456.4 (float)
-345.5 (float)
-lastname2, firstname2 (string)
-3354.7 (float)
-54.6 (float)
-56.2 (float)
-lastname3, firstname3 (string)
-76.6 (float)
-34.2 (float)
-48.2 (float)以此类推...实际上,7个不同的“雇员”后面跟着12组“数字”(一年中的月份)....but这个例子应该足以让你知道我在尝试做什么。
我需要输出employee -Total Sum (列表中12个数字的总和)的每个"employee“-Name的特定信息。
因此,我的逻辑将我带到这个结论,但我不知道从哪里开始:
创建7个不同的数组来存储每个“员工”数据。有了这个逻辑,我需要将主列表拆分成独立的数组,以便我可以使用它们。
如何才能做到这一点?另外,如果我没有预定义的员工数量(而是一个定义的格式::“姓名”,后跟12个月的数字),...how我能做到这一点吗?
我确信,一旦我知道如何将列表“分割”成不同的部分--每13行--我就能想出办法了。
发布于 2012-12-02 07:29:44
我不会创建7个不同的数组。我将创建某种数据结构,以便在一种数据类型(这是python,但您也可以用python创建数据结构)中保存一名员工的所有相关信息。
然后,在处理每个员工的数据时,您所要做的就是迭代一个员工数据元素数组。通过这种方式,可以更容易地跟踪数据的索引(或者甚至消除了跟踪的需要!)。
如果您想以某种方式对数据进行排序,这将特别有用。这样,你只需要对一个数组而不是7个数组进行排序。
发布于 2012-12-02 07:34:38
是的,每隔13行你就会有一位员工的信息。
但是,您可以使用列表字典,而不是使用12个不同的列表,这样您就不必担心员工的数量。
您可以使用定向到每个员工的行数的参数。
您可以执行以下操作:
infile = open("file.txt", "rt")
employee = dict()
name = infile.readline().strip()
while name:
employee[name] = list()
for i in xrange(1, 12):
val = float(infile.readline().strip())
employee[name].append(val)
name = infile.readline().strip()访问字典条目的一些方法:
for name, months in employee.items():
print name
print months
for name in employee.keys():
print name
print employee[name]
for months in employee.values():
print months
for name, months in (employee.keys(), employee.values()):
print name
print months整个过程如下:
infile = open("file.txt", "rt")
employee = dict()
name = infile.readline().strip()
while name:
val = 0.0
for i in xrange(1, 12):
val += float(infile.readline().strip())
employee[name] = val
print ">>> Employee:", name, " -- salary:", str(employee[name])
name = infile.readline().strip()对不起,不知何故,我拐弯抹角了。
发布于 2012-12-02 08:24:01
这里有一个选项。不是很好,但仍然是蛮横的选择。
summed = 0
with open("file.txt", "rt") as f:
print f.readline() # We print first line (first man)
for line in f:
# then we suppose every line is float.
try:
# convert to float
value = float(line.strip())
# add to sum
summed += value
# If it does not convert, then it is next person
except ValueError:
# print sum for previous person
print summed
# print new name
print line
# reset sum
summed = 0
# on end of file there is no errors, so we print lst result
print summed由于您需要更高的灵活性,因此还有另一种选择:
data = {} # dict: list of all values for person by person name
with open("file.txt", "rt") as f:
data_key = f.readline() # We remember first line (first man)
data[data_key] = [] # empty list of values
for line in f:
# then we suppose every line is float.
try:
# convert to float
value = float(line.strip())
# add to data
data[data_key].append(value)
# If it does not convert, then it is next person
except ValueError:
# next person's name
data_key = line
# new list
data[data_key] = []问:假设我想给总销售额超过7000美元(12个月)的员工打印“2%奖金”。
for employee, stats in data.iteritems():
if sum(stats) > 7000:
print employee + " done 7000 in total sales! need 2% bonus"https://stackoverflow.com/questions/13664768
复制相似问题