类型错误子设置字符串列表-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']