python - Python 中一个元组中的所有项目

标签 python tuples

<分区>

我有一个元组,它由一些整数元组和一些整数组成,例如 ((1, 2), 3, (4, 5), 6)。现在我需要所有整数从中。我写道:

def get_all_items(iterable):
    t = []

    for each in iterable:
        if type(each) == int:
            t.append(each)
        else:
            t.extend(each)

    return tuple(t)

它对我有用。有没有更好的方法来做到这一点?

最佳答案

不要忘记作弊方式

>>> from ast import literal_eval
>>> t = ((1, 2), 3, (4, 5), 6)
>>> literal_eval(repr(t).translate(None, '()'))
(1, 2, 3, 4, 5, 6)

关于python - Python 中一个元组中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372671/

相关文章:

python - Flask 中的 Celery 任务,用于上传和调整图像大小并将其存储到 Amazon S3

Python:过滤元组

scala - Scala:如何在Tuple的每个元素上调用trim

python - Python中元组和卡住集之间的区别

python - 如何获取TensorFlow层中的神经元数量?

python - 使用 youtube-dl 和 ffmpeg 库下载修剪后的 youtube 视频的音频数据时遇到问题

python - 从文本文件中读取元组赋值(例如写为 d1 : p, m, h, = 20, 15, 22)并对每个变量执行计算(例如 p*h)

python - List 和 Tuple 中相同操作的不同 ValueError

python - 了解 Tensorflow LSTM 模型输入?

python - 获取按钮名称作为输入