python - 如何从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' 的记录不应出现在输出中。我的错误在哪里?
解决方案
你逻辑错了。
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'])
推荐阅读
- python - 将 numpy 数组的 pandas 列转换为更高维的 numpy 数组
- mysql - 如何从包含不同语言的记录中过滤掉英文记录(包括数字和标点符号)
- mapreduce - 如何减少发出多行的couchdb map函数
- flask - Flask-SocketIO 在 Werkzeug 下运行,WebSocket 不可用。这是什么意思?
- php - 使用带有 android 应用程序的 URL 将图像保存在服务器上 ERROR End of input error at line 1 column 1 path $
- python - 与matplotlib在同一帧上的曲线图和直方图
- sql - 使用分区聚合相邻行
- javascript - await 是保留字 - 从异步函数调用
- mongodb - 访问 MongoDB 聚合结果中的上一个文档
- javascript - 如何在使用渲染方法时在 jQuery 表中设置自动递增的 Id 列