Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
类型错误子设置字符串列表-Python 3_Python_Subset - Fatal编程技术网

类型错误子设置字符串列表-Python 3

类型错误子设置字符串列表-Python 3,python,subset,Python,Subset,我试图从另一个列表中子集一个列表,但我得到了一个TypeError a = ('one', 'two', 'two', 'three', 'four', 'five', 'three', 'three', 'eight', 'nine', 'ten') a = list(a) b = ('two', 'three', 'eight', 'nine') b = list(b) c = [a[i] for i in b] # subsets list a for what's in list b

我试图从另一个列表中子集一个列表,但我得到了一个
TypeError

a = ('one', 'two', 'two', 'three', 'four', 'five', 'three', 'three', 'eight', 'nine', 'ten')
a = list(a)
b = ('two', 'three', 'eight', 'nine')
b = list(b)
c = [a[i] for i in b]  # subsets list a for what's in list b
返回:

TypeError:列表索引必须是整数或片,而不是str

我要找的是:

print(a)
('two', 'two', 'three', 'three', 'three', 'eight', 'nine')

要从
a
获取
b
中的项目:

c = [i for i in a if i in b]
print(c)
输出:

['two', 'two', 'three', 'three', 'three', 'eight', 'nine']
['two', 'two', 'three', 'three', 'three', 'eight', 'nine']
我喜欢这样做:

代码: 测试代码: 结果:
a = ('one', 'two', 'two', 'three', 'four', 'five',
     'three', 'three', 'eight', 'nine', 'ten')
b = {'two', 'three', 'eight', 'nine'}

print(list(filter(lambda x: x in b, a)))
['two', 'two', 'three', 'three', 'three', 'eight', 'nine']