有人可以帮我解决这些问题吗? 基本上我已经开始创建列表,如下所示:
>>> item
[('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
我只想在满足诸如苹果和人口之类的情况下合并对象的结果。这是我想要的最终结果:
>>> item
[('apple', 16, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
任何帮助将不胜感激。
如果问题不清楚,那是我的错:这是我的一些代码。
def add(par):
temp_dict = {}
for name, count, term in par:
if name in temp_dict:
temp_dict[name] += count
else:
temp_dict[name] = count
result = []
for name, count, term in par:
if name in temp_dict:
result.append((name, temp_dict[name], term))
del temp_dict[name]
return result
如何修改该类,使其返回所需的结果? 上面的代码仍然把“apple”加在一起,就是这样:
block 引用> block 引用>item [('apple', 19, 'disease'), ('orange', 6, 'population')]
最佳答案
您可能会达到预期的结果,如下所示:
In [6]: my_items = [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
In [7]: import collections
In [8]: my_counter = collections.defaultdict(int)
In [9]: for i in my_items:
# at this point, i is a tuple, let's unpack it
(fruit, n, category) = i
# use the tuple (fruit, category) as a key.
# note that this has to be a tuple, and not a list
my_counter[(fruit, category)] += n
...:
In [10]: my_counter
Out[10]: defaultdict(<class 'int'>, {('orange', 'population'): 6, ('apple', 'population'): 16, ('apple', 'disease'): 3})
(请注意,这是一个 IPython session ,我强烈推荐使用它,而不是使用 vanilla shell 进行交互式工作)
在此示例中,my_counter
是修改后的 dict
对象。它与“常规”字典的不同之处在于,如果指定的键不可用,则会自动创建默认值(在我们的例子中为整数零)。
从你的例子我知道你是Python新手。如果您需要更多的聚合能力来处理大量数据,您可能需要看看 Pandas .
祝你好运。
编辑为了完整起见,遵循 keimina的answer in this thread ,您可能会考虑使用具有许多 features that are useful for counters 的 collections.Counter
例如 most_common()
函数对我来说是新的。
关于Python 在列表中添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24929660/