我有两个清单:
a_list
包含不同的tupled id:
a_list = [('1'), ('2'), ('3'), ('4')...etc]
并列在名为check_list
的元组列表中:
check_list = [[[('1'), ('2')]], [[('2'), ('3')], [('3'),('4')]], [[('1'),('3')]]...etc]
我的问题对于我的python技能级别来说有点过于复杂......我正在尝试形成一个矩阵输出到csv文件,具有以下结构:
1 2 3 4
1 1 1 0 0
2 0 1 2 1
3 1 0 1 0
其中每个值都是a_list
中check_list
的数字的计数。
我看过numpy而且我不知道。我和this一起玩过,但我似乎无法完全理解将其转移到我的问题上。我对阵列知识也非常有限。提前谢谢。
答案 0 :(得分:1)
您可以使用Counter dict获取计数,按键排序以使用OrderedDict获取Order中的计数以维护该顺序并使用document.querySelectorAll("td[id^=cell]")
查找缺少的键。
dict.viewkeys
输出:
from __future__ import print_function
from collections import Counter, OrderedDict
from itertools import chain
check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]
a_list = [('1',), ('2',), ('3',), ('4',)]
cn = OrderedDict(sorted(Counter(a_list).items()))
print(" ".join([str(t[0]) for t in cn]))
for chk in check_list:
_cn = Counter(chain(*chk))
# cn.keys() python 3
diff = cn.viewkeys() - _cn
for k in cn:
if k not in diff:
print(_cn[k], end=" ")
else:
print(0, end=" ")
print()
如果您不关心订单,可以删除sorted / Ordereddict逻辑:
1 2 3 4
1 1 0 0
0 1 2 1
1 0 1 0
这会给你一个任意的顺序:
from collections import Counter
from itertools import chain
check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]
a_list = [('1',), ('2',), ('3',), ('4',)]
cn = Counter(a_list)
print(" ".join([str(t[0]) for t in cn]))
for chk in check_list:
_cn = Counter(chain(*chk))
diff = cn.viewkeys() - _cn
for k in cn:
if k not in diff:
print(_cn[k], end=" ")
else:
print(0, end=" ")
print()
写入csv:
3 4 1 2
0 0 1 1
2 1 0 1
1 0 1 0
out.csv:
from collections import Counter, OrderedDict
from itertools import chain
from csv import writer
check_list = [[[('1',), ('2',)]], [[('2',), ('3',)], [('3',), ('4',)]], [[('1',), ('3',)]]]
a_list = [('1',), ('2',), ('3',), ('4',)]
with open("out.csv","w") as out:
wr = writer(out,delimiter=" ")
cn = OrderedDict(sorted(Counter(a_list).items()))
wr.writerow(list(chain(*cn)))
for chk in check_list:
_cn = Counter(chain(*chk))
diff = cn.viewkeys() - _cn
wr.writerow([_cn[k] if k not in diff else 0 for k in cn])