简体   繁体   English

将元组与元组的元组区分开

[英]Differentiating a tuple from a tuple of tuples

I have a tuple, and a tuple of tuples. 我有一个元组和一个元组。

import numpy as np
a = ("Control", "Group1")
b = (("Control", "Group1"), ("Control", "Group1", "Group2))

How can I tell that a is fundamentally different from b ? 我怎么知道ab根本不同? Both

print(len(a))
print(np.shape(a))
print(len(np.shape(a)))

and

print(len(b))
print(np.shape(b))
print(len(np.shape(b)))

produce the same output: 产生相同的输出:

2
(2,)
1

Thanks in advance again! 再次感谢您!

You cannot, because they are not fundamentally different. 您不能,因为它们没有根本的不同。

What should happen for the following? 接下来会发生什么?

c = (("Foo", "bar"), "baz")

It's also a tuple, and it contains both "bare" values as well as another tuple. 它也是一个元组,并且包含“裸”值以及另一个元组。

If you need to detect tuples which only consist of tuples, use: 如果需要检测仅包含元组的元组,请使用:

if all(isinstance(element, tuple) for element in a)

If you need to detect tuples which only consist of non-tuples, use: 如果需要检测仅包含非元组的元组,请使用:

if not any(isinstance(element, tuple) for element in a)

Both of the above are have a time complexity of O(n) (with n being the number of elements in a ), which may not be desirable depending from where your data is coming. 上面两个都具有O(n)的时间复杂度(其中na中元素的数量),根据数据的来源,这可能不是理想的。 It is however unavoidable, unless you are willing to take the risk not actually having tuples of tuples. 但是,这是不可避免的,除非您愿意冒险不真正拥有元组。

Depending on what you're doing with your data, you might actually want to check for a sequence of sequences. 根据您对数据的处理方式,您实际上可能想要检查序列序列。 In that case, you should use the Sequence ABC ( Python 2 ): 在这种情况下,您应该使用Sequence ABCPython 2 ):

import collections.abc
if all(isinstance(element, collections.abc.Sequence) for element in a)

Use the equality operator, == : 使用等于运算符==

>>> a = ("Control", "Group1")
>>> b = (("Control", "Group1"), ("Control", "Group1", "Group2"))
>>> a == b
False

If you just want a vague idea of the general structure, and the string elements won't contain parentheses, you can count the parentheses: 如果您只是想对通用结构有一个模糊的想法,并且字符串元素将不包含括号,则可以计算括号:

>>> str(a).count('(')
1
>>> str(b).count('(')
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM