【问题标题】:Fetch specific values from nested tuples in a list从列表中的嵌套元组中获取特定值
【发布时间】:2019-08-12 16:34:09
【问题描述】:

我在列表中有一个嵌套元组,如下所示:

x = [(('subject', 'to'), 18), (('subject', 'and'), 5), (('subject', 'of'), 4), (('subject', 'the'), 3), (('subject', 'that'), 2), (('subject', 'owing'), 2), (('subject', 'making'), 2)]

我需要一个内部元组的第二个值(索引 1)的列表。如何列出?

我需要什么作为输出:

['to','and','of','the','that','owing','making']

按特定顺序

这是我尝试过的

x[0][0][1]

我的输出

to

【问题讨论】:

  • 只需迭代并获取所需索引处的值。 listtuple 都支持索引。如果您需要其他帮助,请尝试再次发布。现在投票结束
  • 这看起来像是你的作业。我能问一下你试图解决这个问题吗?只需查找元组和列表推导即可为您指明方向。

标签: python list filter tuples


【解决方案1】:

使用列表推导和变量解包:

newList = [j for (i, j), index in x]

【讨论】:

    【解决方案2】:

    您也可以使用map 来执行此操作:

    x = list(map(lambda el: el[0][1],x))
    print(x)
    

    结果:

    ['to', 'and', 'of', 'the', 'that', 'owing', 'making']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      相关资源
      最近更新 更多