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>]
答案 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))