Python-如何在给定许多索引的情况下打印列表的值?
例如,我有索引值:Python-如何在给定许多索引的情况下打印列表的值?,python,list,printing,indices,Python,List,Printing,Indices,例如,我有索引值: x = [1, 4, 5, 7] 我有一个元素列表: y = ['this','is','a','very','short','sentence','for','testing'] 我想返回值 ['is','short','sentence','testing'] 当我试图打印时,请说: y[1] 它将很高兴地返回['is']。但是,当我执行打印(y[x])时,它将不返回任何内容。如何打印所有这些索引?奖励:然后将它们连接在一起。这应该可以完成以下工作: ' '.jo
x = [1, 4, 5, 7]
我有一个元素列表:
y = ['this','is','a','very','short','sentence','for','testing']
我想返回值
['is','short','sentence','testing']
当我试图打印时,请说:
y[1]
它将很高兴地返回
['is']
。但是,当我执行打印(y[x])
时,它将不返回任何内容。如何打印所有这些索引?奖励:然后将它们连接在一起。这应该可以完成以下工作:
' '.join([y[i] for i in x])
这应该可以做到:
' '.join([y[i] for i in x])
尝试此列表comp
[y[i]代表x中的i]
>>> 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']
尝试此列表comp
[y[i]代表x中的i]
>>> 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']
您将需要一个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
您将需要一个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
如果您有
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']
如果您有
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']
你说加入是什么意思?你说加入是什么意思?