get the count of elements of tuples of your own...not just the range or sequence(获取您自己的元组元素的数量......不仅仅是范围或序列)
问题描述
下面的代码正在运行这个列表元组的前三个元素
The below code is running for first three elements of the tuple of this list
SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]
from collections import Counter
c = Counter(elem[0:3] for elem in SS1)
for k, v in c.items():
if (v > 0):
print(k,v)
输出是:
(1, 2, 3) 3
(1, 2, 4) 1
(1, 3, 4) 1
(2, 3, 4) 1
但我的期望不仅仅是前三个元组......我想要元组 (0,2,3)
或元组 (1,2,4)
的计数器代码> 同样,我可以传递元组的任何三个位置并获取它的计数......我该怎么做?
But my expectation is not just for first three tuple...i want the counter for tuple (0,2,3)
or tuple (1,2,4)
likewise i can pass any three position of the tuple and get the count of it... How can I do this?
推荐答案
如果我从你的问题中理解是正确的,下面的代码将解决你的问题:
If what i understood from your question is correct, the code below will solve your issue:
SS1=[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 5, 6), (1, 2, 4, 5, 6), (1, 3, 4, 5, 6), (2, 3, 4, 5, 6)]
from collections import Counter
def get_new_list(a, pos):
# Check if any element in pos is > than the length of the tuples
if any(k >= len(min(SS1, key=lambda x: len(x))) for k in pos):
return
for k in a:
yield tuple(k[j] for j in pos)
def elm_counter(elm):
if not len(elm):
return
c = Counter(elm)
for k, v in c.items():
if v > 0:
print(k, v)
elm = list(get_new_list(SS1, (0, 2, 4)))
elm_counter(elm)
print('---')
elm = list(get_new_list(SS1, (1, 2, 4)))
elm_counter(elm)
输出:
(1, 3, 5) 1
(1, 3, 6) 2
(1, 4, 6) 2
(2, 4, 6) 1
---
(2, 3, 6) 2
(2, 3, 5) 1
(3, 4, 6) 2
(2, 4, 6) 1
这篇关于获取您自己的元组元素的数量......不仅仅是范围或序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取您自己的元组元素的数量......不仅仅是范围或序列


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01