这是我的Python代码。我希望这段代码可以单行编写(写一行而不是六行)。感谢您的帮助
for query in announcements:
try:
query.price = int(query.price)
listme.append(query.price)
except:
print(listme)
这基本上会做同样的事情,而不会打印失败:
listme = [int(query.price) for query in announcements if query.price.isdigit()]
这假设query.price
是一个字符串。
也尝试打印失败将是棘手的(并且不可读),但是可能:
listme = [x for x in [int(query.price) if query.price.isdigit() else print(query.price) for query in announcements] if x is not None]
c = query.price = int(query.price)
b = listme.append(query.price)
a = c if c is not None else b