使用列表中的值过滤元组

时间:2017-01-28 11:24:38

标签: python

我有以下数据集:

test_set = ("The sun in the sky", "The sun in the light", "Do not blame it on moonlight", "Do not blame it on sunshine")

如果根据列表过滤此测试,我现在想做什么。所以喜欢

y = [0,1]
test_set_2 = test_set[y]

然而,这给了我以下错误:

Traceback (most recent call last):
File "/Users/marcvanderpeet/PycharmProjects/untitled/test3.py", line 5, in <module>
test_set_2 = test_set[y]
TypeError: tuple indices must be integers, not list

关于如何获得我想要的结果的任何想法:

test_set_2 = ("The sun in the sky", "The sun in the light")

1 个答案:

答案 0 :(得分:2)

您可以浏览索引列表并从大列表中提取相关项目。

test_set = ("The sun in the sky", "The sun in the light", "Do not blame it on moonlight", "Do not blame it on sunshine")

y = [0,1]
test_set_2 =  tuple([test_set[index] for index in y])

print test_set_2