我有索引值:
x = [1, 4, 5, 7]
我有一个元素列表:
y = ['this','is','a','very','short','sentence','for','testing']
我想返回值
['is','short','sentence','testing']
当我尝试打印时说:
y[1]
很乐意回复['is']
。但是,当我print(y[x]))
时,它只会返回任何内容。如何打印所有这些索引?奖金:然后加入他们。
答案 0 :(得分:2)
试试此列表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']
答案 1 :(得分:1)
这应该做的工作:
' '.join([y[i] for i in x])
答案 2 :(得分:1)
您将需要一个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
答案 3 :(得分:0)
如果您有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']