python - 尝试打印包含 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
解决方案
您可以使用内置isinstance
函数:
str_only = [i for i in C if isinstance(i, str)]
推荐阅读
- mysql - MySql:在 UNION ALL 结果中保留顺序
- c# - C# 随机分割字符串
- javascript - vuex 未知动作类型:使用 typescript 应用程序的 VueJS 中的 RawHTML
- c# - Entity Framework 究竟在什么操作中打开和关闭数据库连接?
- c# - 如何使用 C# 从 .txt 文件中获取随机单词?
- css - 根据屏幕大小更改高度
- java - JDA 提到的成员 - 不工作的命令
- rust - Rocket 内的车把助手
- css - CSS显示表格在分隔边框之间添加空间
- django - Docker 映像未运行,数据库错误:django.db.utils.OperationalError 无法将主机名“postgres”转换为地址:名称或服务未知