【问题标题】:Python - how to print values of a list given many indexes?Python - 如何在给定许多索引的情况下打印列表的值?
【发布时间】:2015-04-02 07:11:29
【问题描述】:

例如,我有索引值:

x = [1, 4, 5, 7]

我有一个元素列表:

y = ['this','is','a','very','short','sentence','for','testing']

我想返回值

['is','short','sentence','testing']

当我尝试打印时说:

y[1]

它会很高兴返回['is']。但是,当我执行print(y[x])) 时,它只会返回任何内容。如何打印所有这些索引?奖励:然后将它们连接在一起。

【问题讨论】:

  • 加入是什么意思?

标签: python list printing indices


【解决方案1】:

试试这个列表 comp [y[i] for i in x]

>>> y = ['this','is','a','very','short','sentence','for','testing']
>>> x = [1, 4, 5, 7]
>>> [y[i] for i in x]                    # List comprehension to get strings
['is', 'short', 'sentence', 'testing']
>>> ' '.join([y[i] for i in x])          # Join on that for your bonus
'is short sentence testing'

其他方式

>>> list(map(lambda i:y[i], x) )         # Using map
['is', 'short', 'sentence', 'testing']

【讨论】:

    【解决方案2】:

    这应该可以完成工作:

    ' '.join([y[i] for i in x])
    

    【讨论】:

      【解决方案3】:

      您将需要一个 for 循环来遍历您的索引列表,然后使用索引对您的列表进行轴化。

      for i in x: #x is your list, i will take the 'value' of the numbers in your list and will be your indexed
          print y[i]
      
          > is
            short
            sentence
            testing
      

      【讨论】:

        【解决方案4】:

        如果你有numpy 包,你可以这样做

        >>> import numpy as np
        >>> y = np.array(['this','is','a','very','short','sentence','for','testing'])
        >>> x = np.array([1,4,5,7])
        >>> print y[x]
        ['is' 'short' 'sentence' 'testing']
        

        【讨论】:

          猜你喜欢
          • 2021-08-24
          • 2022-12-13
          • 2019-09-08
          • 1970-01-01
          • 1970-01-01
          • 2022-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多