首页 > 解决方案 > 如何从if in for循环中获得正确的输出

问题描述

a=  ['Emre', 'Hacettepe', 'University', 'Computer', 'Engineering']
b=  ['Kerem', 'METU', 'Architecture']
c=  ['Leyla', 'Ankara', 'University', 'Physics']
d=  ['Sami', 'Bilkent', 'University', 'Civil', 'Engineering'] 

#S=input list 我写的参数,但我没有在这里添加所有代码,因为它太长了。等输入:Emre,Ahmet

x=len(S)
for i in range(0,x):
    list=[]
    if a[0]== S[i] :
        print('Name: '+ (a[0])+', University: '+a[1]+' '+a[2]+','+a[3]+' '+a[4],end=' ')
        list.append(S[i])
    if h[0]== S[i]:
        print('Name: '+ (h[0])+', University: '+h[1]+' '+h[2]+','+h[3]+' '+h[4],end=' ')
        list.append(S[i])
    if e[0]==S[0]:
        print('Name: '+e[0]+', University: '+e[1]+','+e[2],end=' ')
        list.append(S[i])
    if f[0]==S[i]:
        print('Name: '+f[0]+', University: '+f[1]+' '+f[2]+','+f[3],end=' ')
        list.append(S[i])
    if a[0] or h[0] or e[0] or f[0]!= S[i] and S[i] not in list:
        print('No record of '+"'"+S[i]+"'"+' was found!',end=' ')

在最后一个“if”语句中,我只想写不存在的,但我收到了错误的输出。

Name: Emre, University: Hacettepe University,Computer Engineering No record of 'Emre' was found! No record of 'Ahmet' was found!

'Emre' 的记录不应出现在输出中。我的错误在哪里?

标签: pythonarrayspython-3.x

解决方案


你逻辑错了。

if a[0] or h[0] or e[0] or f[0]!= S[i] and S[i] not in list:
        print('No record of '+"'"+S[i]+"'"+' was found!',end=' ')

应该

if a[0] != S[i] and h[0] != S[i] and e[0] != S[i] and f[0] != S[i] and S[i] not in list:
        print('No record of '+"'"+S[i]+"'"+' was found!',end=' ')

一个更清晰的方法是

if S[i] not in [a[0],b[0],c[0],d[0]]:
        print('No record of '+"'"+S[i]+"'"+' was found!',end=' ')

list(注意 S[i]如果不在广告中,则永远不会出现)

更好的方法是

students = {}
students['Emre'] = {'University':'Hacettepe', 'Course': 'Computer Engineering'}
students['Kerem'] =  {'University':'METU', 'Course': 'Architecture'}

for name in students:
    print(name,students[name]['University'],", University, ",students[name]['Course'])

推荐阅读