使用循环查找两个列表之间的差异

时间:2017-10-31 21:48:28

标签: python loops

我试图找到用户提示的两个列表之间的差异。

facebookF = [ ]
partyA = [ ]
add_facebookF_option = 'Y'
while add_facebookF_option == 'Y':
    facebookF.append(input('What friends do Alice have in her Facebook? '))
    add_facebookF_option = input('Type Y to add more friend for Alice. Type others if no.')

add_partyA_option = 'Y'
while add_partyA_option =='Y':
    partyA.append(input('Who is attending the party?'))
    add_partyA_option = input('Is there any others attending the party? Type Y if yes, type others if no.')


print(facebookF)
print(partyA)

notInvited=[]
list3 = facebookF + partyA 
for i in range(len(list3)):
    if (list3[i] not in facebookF) or (list3[i] not in partyA):
        notInvited.append(list3[i])   
print(notInvited)

如果用户在列表的输入中没有输入任何内容,则它具有以下输出:

What friends do Alice have in her Facebook?         #pressed enter, Alice has no friends.
Type Y to add more friend for Alice. Type others if no.N
Who is attending the party?1
Is there any others attending the party? Type Y if yes, type others if no.Y
Who is attending the party?2
Is there any others attending the party? Type Y if yes, type others if no.Y
Who is attending the party?3
Is there any others attending the party? Type Y if yes, type others if no.N
['']
['1', '2', '3']
['', '1', '2', '3']

如何清除列表中的''空字符串? 或者确切地说,如何制作一个没有打印出来的空列表? 抱歉,还没有格式化我的代码。

1 个答案:

答案 0 :(得分:0)

首先避免在列表中输入空字符串:

facebookF = [ ]
partyA = [ ]
add_facebookF_option = 'Y'
while add_facebookF_option == 'Y':
    a = input('What friends do Alice have in her Facebook? ')
    if a:
        facebookF.append(a)
    add_facebookF_option = input('Type Y to add more friend for Alice. Type others if no.')

add_partyA_option = 'Y'
while add_partyA_option =='Y':
    a = input('Who is attending the party?')
    if a:
        partyA.append(a)
    add_partyA_option = input('Is there any others attending the party? Type Y if yes, type others if no.')


print(facebookF)
print(partyA)

notInvited=[]
list3 = facebookF + partyA 
for i in range(len(list3)):
    if (list3[i] not in facebookF) or (list3[i] not in partyA):
        notInvited.append(list3[i])   
print(notInvited)