首页 > 解决方案 > 尝试打印包含 int 和 str 的列表,但不打印整数

问题描述

我正在编写一个从两个列表中打印常见项目的代码

def compare_lists_same(list3, list4):
    common =[j for j in list4 if j in list3]
    return common
A = ['beef','chicken','steak','fish','plants', 1, 2]
B = ['plants','steak','cheese', 1, 2, 3, 4, 5]
ignore_case = False
print('First list:'+str(A))
print('Second list'+str(B))
C = compare_lists_same (A,B)
print('The common items from the lists are'+str(C))

这将打印“列表中的常见项目是 ['plants', 'steak', 1, 2]”

我如何告诉函数打印没有整数的列表,所以只会打印 str

标签: python

解决方案


您可以使用内置isinstance函数:

str_only = [i for i in C if isinstance(i, str)]

推荐阅读