我有两个列表,看起来像:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
我希望用list2
中的元素过滤list1
的子串,并获得以下期望输出:
outcome = ['bj-100-cy', 'sh-200-pd']
当你执行以下操作时:
list1 = str(list1)
list2 = str(list2)
outcome = [x for x in list2 if [y for y in list1 if x in y]]
我得到了这样的结果:
['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']']
。我应该如何正确过滤它?谢谢。相关参考资料: 在Python中,是否可以通过另一个字符串列表来过滤子字符串列表?
list2 = [str(x) for x in list2]
,否则我会得到TypeError: 'in <string>' requires string as left operand, not int
。 - ah bonstr(j)
中进行了类型转换:any(i for j in list2 if str(j) in i)
。 - heemayl