【问题标题】:How do I access the list in the tuple?如何访问元组中的列表?
【发布时间】:2018-04-24 16:13:46
【问题描述】:

假设我有一个元组,其中存储了一个列表。

例如:

t = (1, 2, 3, 4 [5, 6, 7])

好吧,我想要将它们保存在元组和列表中的所有数字。我怎么做?另外,我知道如何获取它们保存在元组中的数字。我只需解压元组并获取保存在 lis 中的所有数字,我将对其进行迭代。但在这种情况下,我不知道该怎么办。

有什么想法吗?

更多详情

def work_with_tuple(my_tuple = None):

    count_items = len(my_tuple)

    if count_items == 2:

        first_item, second_item = my_tuple

        print "first_item", first_item
        print "second_item", second_item

    if count_items == 3:

        first_item, second_item, third_item = my_tuple

        print "first_item", first_item
        print "second_item", second_item

        # But I have to know, that 'third_item' is a list.
        # Should I check every unpacked item if it is a list?
        # I think my idea it doesn't sound elegance.
        one, two = third_item
        print "one", one
        print "two", two

print "run first"
print "---------"
#   I call the function with easy tuple
work_with_tuple(my_tuple = (2, 3))
#   output: first_item 2
#           second_item 3
print ""
print "run second"
print "----------"
#   I call the function with nested tuple
work_with_tuple(my_tuple = (2, 3, [4, 6]))
#   output: first_item 2
#   second_item 3
#   one 4
#   two 6

【问题讨论】:

  • 你期待的输出是[1, 2, 3, 4, 5, 6, 7] 吗?
  • 要访问元组中的列表,请使用t[-1]
  • @Aran-Fey 主要是因为 3.x 中的答案是完全容易的,扩展解包和/或库中的新方法是 2.x 所没有的——如果 OP 肯定在 2.7 上- 那么对于推荐OP不可能使用的重复或答案的人来说,这是浪费时间。在这些情况下,2.7 标记和主标记最有用,作为对 OP 可能或可行的限制。
  • @Aran-Fey:请不要删除标签。 OP 显然使用的是 Python 2,该标签有助于传达这一点,在 Python 2 上遇到类似问题的人可以使用该标签找到这篇文章。这里很合适。如果您想用 Py3 解决方案来回答,那就这样吧,但在这种特定情况下,我希望首先解决 Python 2 问题的有用答案,也许作为额外的 Python 3 的奖励。
  • @Aran-Fey:对于这个纯粹的问题来说,这太元了。我们可以将其移至 Python 聊天室或 Meta 吗?

标签: python python-2.7 list tuples


【解决方案1】:

您可以遍历元组并检查每个项目。

def unpack(t):
    numbers = []

    for item in t:
        if isinstance(item, list):
            numbers += item # add each item of the list into accumulator
        else:
            numbers.append(item)

    return numbers

如果您需要更通用的内容,请参阅this answer

【讨论】:

    【解决方案2】:

    这种方式访问​​元组中的列表。

    tl = (1,2,3,4,[5,6,7])
    print tl
    for i in tl:
        if isinstance(i, list):
            print i[2]
        else:
            print i
    

    我希望您的问题正在使用我的代码解决。

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多