Skip to main content
 首页 » 编程设计

python之这个 List Overlap 程序给出了奇怪的输出

2025年05月04日23tintown

我正在做一个练习,在这个练习中我们制作了两个列表,然后我们必须创建一个程序来返回一个列表,该列表只包含列表之间的公共(public)元素。

我把代码写成-

print('Please type in your list number 1') 
list_1=input()  
 
print('Great! Please type in your list number 2 ') 
list_2=input() 
 
commonlist=[] # this will be the list containing common elements. 
 
 
for i in range(len(list_1)): 
    if list_1[i] in list_2: 
        commonlist.append((list_1[i])) # this will put the common elements between the two lists in commonlist 
 
print(commonlist) 

现在,如果我的 list_1 是 [1,2,3,4,5] 而我的 list_2 是 [ 3,4,5,6,7,8,9] 那么预期的输出应该是

[3,4,5]

但是输出是

[‘[', ',', ',', '3', ',', '4', ',', '5', ']']

为什么我会得到这个输出?

请您参考如下方法:

你得到奇怪输出的原因是因为 input() 返回一个字符串。所以你迭代的是字符串而不是列表。

您可以通过使用 str.split() 从输入创建值列表来解决此问题:

print('Please type in your list number 1') 
list_1=input().split() 
 
print('Great! Please type in your list number 2 ') 
list_2=input().split() 

请注意,您的输入必须以空格分隔。

另请注意,如果顺序无关紧要,您可以在此处使用 set():

>>> a = [1, 2, 3, 4] 
>>> b = [2, 6, 1, 8] 
>>>  
>>> set(a) & set(b) 
{1, 2} 
>>>