[英]Merging two lists with different lengths in python and counting elements
I have a list as follows: [[a,a,b,a,b,b,b],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]我有一个列表如下:[[a,a,b,a,b,b,b],[5,5,4,5],[5,1,5],[2,5],[4 ,5],[5],[3],[5]]
The number of lists containing numerical values is the same as the elements in the first list (that contains letters "a" or "b").包含数值的列表的数量与第一个列表(包含字母“a”或“b”)中的元素相同。 The length of the lists containing numbers is unknown a priori.
包含数字的列表的长度是先验未知的。
Each letter corresponds to a list in this way:每个字母以这种方式对应一个列表:
a --> 5,5,4,5一个 --> 5,5,4,5
a --> 5,1,5一 --> 5,1,5
b --> 2,5 b --> 2,5
a --> 4,5一个 --> 4,5
b --> 5 b --> 5
b --> 3 b --> 3
b --> 5 b --> 5
And then, count each value by letters "a" or "b", while keeping the values, for example "a" has in total 6 "5", 2 "4", and 1 "1".然后,将每个值按字母“a”或“b”计数,同时保留值,例如“a”共有 6 个“5”、2 个“4”和 1 个“1”。 "b" has in total 3 "5", 1 "2", and 1 "3".
“b”一共有3个“5”,1个“2”,1个“3”。
Expected result:预期结果:
"a" has in total 6 "5", 2 "4", and 1 "1". “a”一共有6个“5”,2个“4”,1个“1”。
"b" has in total 3 "5", 1 "2", and 1 "3". “b”一共有3个“5”,1个“2”,1个“3”。
One approach:一种方法:
from collections import Counter, defaultdict
lst = [["a", "a", "b", "a", "b", "b", "b"], [5, 5, 4, 5], [5, 1, 5], [2, 5], [4, 5], [5], [3], [5]]
result = defaultdict(Counter)
head, *tail = lst
for key, values in zip(head, tail):
result[key] += Counter(values)
for key, counts in result.items():
print(key, counts)
Output Output
a Counter({5: 6, 4: 2, 1: 1})
b Counter({5: 3, 2: 1, 3: 1})
An alternative:替代:
head, *tail = lst
counts = Counter((key, value) for key, values in zip(head, tail) for value in values)
result = defaultdict(dict)
for (key, value), count in counts.items():
result[key][value] = count
for key, value in result.items():
print(key, value)
Output Output
a {5: 6, 4: 2, 1: 1}
b {2: 1, 5: 3, 3: 1}
This would be my approach:这将是我的方法:
inputs = [['a','a','b','a','b','b','b'],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]
counts = {}
for k, v in zip(inputs[0], inputs[1:]):
if k in counts.keys():
counts[k] += v
else:
counts[k] = v
My output for this:我的 output 为此:
{'a': [5, 5, 4, 5, 5, 1, 5, 4, 5], 'b': [2, 5, 5, 3, 5]}
Then you can use Counters, len(), etc. to get the exact output formatting you want.然后你可以使用计数器、len() 等来获得你想要的精确 output 格式。
See below ( Counter
and defaultdict
are the main "players")见下文(
Counter
和defaultdict
是主要的“玩家”)
from collections import Counter,defaultdict
results = defaultdict(Counter)
data = [['a','a','b','a','b','b','b'],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]
for idx,x in enumerate(data[0],1):
results[x].update(data[idx])
for letter,counter in results.items():
print(f'{letter} -> {counter}')
output output
a -> Counter({5: 6, 4: 2, 1: 1})
b -> Counter({5: 3, 2: 1, 3: 1})
It's a fun problem to solve.这是一个有趣的问题。
from collections import Counter
data = [['a','a','b','a','b','b','b'],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]
counts = { k:Counter() for k in list(set(data[0])) }
for i, k in enumerate(data[0], 1):
counts[k].update(data[i])
print(counts)
# {'a': Counter({5: 6, 4: 2, 1: 1}), 'b': Counter({5: 3, 2: 1, 3: 1})}
l = [["a","a","b","a","b","b","b"],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]
d = {}
for i in l[0]:
if i not in d.keys():
d[i] = []
for i, item in zip(l[0],l[1:]):
d[i].append(item)
count_dict = {}
for i in d.keys():
count_dict[i] = {}
for j in d[i]:
elements = set(j)
for k in elements:
if str(k) not in count_dict[i].keys():
count_dict[i][str(k)] = j.count(k)
else:
count_dict[i][str(k)] += j.count(k)
for i,j in count_dict.items():
print('{} has {}'.format(i,j))
First off, you should really be doing your own homework首先,你真的应该自己做功课
... I just love a good algo problem ( adventOfCode
, anyone?) ...我只是喜欢一个好的算法问题(
adventOfCode
,有人吗?)
Steps:脚步:
"
around strings in the list"
在列表中的字符串周围"a"
and "b"
"a"
和"b"
中的计数l[0][sublist_index - 1]
l[0][sublist_index - 1]
if v not in d[bucket].keys(): d[bucket][v] = 0
if v not in d[bucket].keys(): d[bucket][v] = 0
v
, in the appropriate bucket: d[bucket][v] += 1
v
的计数器: d[bucket][v] += 1
l = [["a","a","b","a","b","b","b"],[5,5,4,5],[5,1,5],[2,5],[4,5],[5],[3],[5]]
d = {"a": {}, "b": {}}
for sublist_index in range(1, len(l)):
bucket = l[0][sublist_index - 1]
for v in l[sublist_index]:
if v not in d[bucket].keys():
d[bucket][v] = 0
d[bucket][v] += 1
print(d)
and the output:和 output:
{'a': {5: 6, 4: 2, 1: 1}, 'b': {2: 1, 5: 3, 3: 1}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.