-1

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

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

4

5 回答 5

1

您可以使用内置isinstance函数:

str_only = [i for i in C if isinstance(i, str)]
于 2021-09-23T05:25:44.780 回答
0

我会编写一个循环遍历列表的函数,并在打印之前检查每个值的类型。像这样的东西:

def print_list_of_strings(list_to_print):
    s = "["
    for value in list_to_print:
        if type(value) != 'int':
            s += '"' + value + '", '
    s = s[:len(s) - 2] + ']'
    print(s) # or return s 
于 2021-09-23T05:40:43.190 回答
0

尝试这个:

output = [val for val in C if isinstance(val, str)]

print(output)

输出:

['plants', 'steak']

于 2021-09-23T05:25:45.383 回答
0

只需将功能更改为:

def compare_lists_same(list3, list4):
    list3 = [i for i in list3 if type(i)==str]
    list4 = [i for i in list4 if type(i)==str]
    common =[j for j in list4 if j in list3]
    return common
于 2021-09-23T05:31:50.057 回答
0

这应该可以解决问题:

a = ['beef','chicken','steak','fish','plants', 1, 2]
b = ['plants','steak','cheese', 1, 2, 3, 4, 5]

a2 = []
b2 = []

for ele in a:
    if(type(ele)==str):
        a2.append(ele)
    else:
        pass
    
for ele in b:
    if(type(ele)==str):
        b2.append(ele)
    else:
        pass

print(a2)
print(b2)
于 2021-09-23T05:47:43.170 回答