如果/否则,则无法运行Python

时间:2018-07-27 07:09:00

标签: python python-3.x if-statement

s_headers=[]
headers=['DRIVER’S NAME', 'LICENSE', 'PH NUMBER', 'DOB', 'HIRE DAY']
for head in headers:
    if isinstance(head, float):
        s_headers.append(str(int(head)))
    else:
        s_headers.append(head)
print(s_headers)

输出:-

  

[“驾驶员姓名”,“许可”,“ PH号码”,“ DOB”,“ HIRE DAY”]

当我尝试使用此代码减少代码时,

s_headers.append(str(int(head) if (isinstance(head, float)) else head) for head in headers)
print(s_headers)

输出:-

  

[at 0x7f2aeec50780>]

2 个答案:

答案 0 :(得分:1)

您似乎需要列表理解

例如:

s_headers=[]
headers=['DRIVER’S NAME', 'LICENSE', 'PH NUMBER', 'DOB', 'HIRE DAY']

s_headers = [str(int(head)) if isinstance(head, float) else head  for head in headers]
print(s_headers)

答案 1 :(得分:1)

s_headers.append(str(int(head) if (isinstance(head, float)) else head) for head in headers)

创建一个生成器表达式,该表达式在需要成员之前不会求值。您可以进行列表理解:

s_headers = [str(int(head) if (isinstance(head, float)) else head) for head in headers]
print(s_headers)

或将结果强制转换(生成器到列表中):

s_headers.extend(list(str(int(head) if (isinstance(head, float)) else head) for head in headers))